Android以编程方式触发长按HOME

时间:2017-07-13 21:02:06

标签: android keyevent

我正试图想出一种以编程方式模仿长按HOME按钮的动作的方法。我有BACK按钮使用以下代码:

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按钮?

提前感谢您的帮助。 安德鲁

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

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。这可能有所帮助。