我正在尝试找到一种以编程方式模仿长按HOME按钮的操作的方法。我有使用以下代码的“返回”按钮:
this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
但是当我尝试模仿(长)HOME时,按相同的方式:
this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HOME));
// Thread.sleep(1000); Perhaps for long press?
this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HOME));
没有任何反应。还有其他方法可以模仿按下HOME按钮吗?
您可以尝试以下方法:
this.dispatchKeyEvent(new KeyEvent((long) ViewConfiguration.getLongPressTimeout(), (long) 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HOME), 0); // ViewConfiguration.getLongPressTimeout() returns the duration in milliseconds before a press turns into a long press
它使用此构造函数:
/**
* Create a new key event.
*
* @param downTime The time (in {@link android.os.SystemClock#uptimeMillis})
* at which this key code originally went down.
* @param eventTime The time (in {@link android.os.SystemClock#uptimeMillis})
* at which this event happened.
* @param action Action code: either {@link #ACTION_DOWN},
* {@link #ACTION_UP}, or {@link #ACTION_MULTIPLE}.
* @param code The key code.
* @param repeat A repeat count for down events (> 0 if this is after the
* initial down) or event count for multiple events.
*/
public KeyEvent(long downTime, long eventTime, int action,
int code, int repeat) {
mDownTime = downTime;
mEventTime = eventTime;
mAction = action;
mKeyCode = code;
mRepeatCount = repeat;
mDeviceId = KeyCharacterMap.VIRTUAL_KEYBOARD;
}
请参见this。这可能会有所帮助。