Android通过编程触发长时间的主按键

Android通过编程触发长时间的主按键,android,keyevent,Android,Keyevent,我试图找出一种方法,通过编程模拟长时间按下主按钮的动作。我有后退按钮,使用以下代码: this.dispatchKeyEvent(新的KeyEvent(KeyEvent.ACTION\u DOWN,KeyEvent.KEYCODE\u BACK)); dispatchKeyEvent(新的KeyEvent(KeyEvent.ACTION\u UP,KeyEvent.KEYCODE\u BACK)) 但当我试着以同样的方式模仿(长)本垒打时: this.dispatchKeyEvent(new K

我试图找出一种方法,通过编程模拟长时间按下主按钮的动作。我有后退按钮,使用以下代码:

this.dispatchKeyEvent(新的KeyEvent(KeyEvent.ACTION\u DOWN,KeyEvent.KEYCODE\u BACK));
dispatchKeyEvent(新的KeyEvent(KeyEvent.ACTION\u UP,KeyEvent.KEYCODE\u BACK))

但当我试着以同样的方式模仿(长)本垒打时:

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));
什么也没发生。有没有其他方法来模拟按下主页按钮?

您可以尝试以下方法:

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;
}

看。这可能会有帮助。

就我所知,我想问一下,我能知道长按Home按钮的主要目的是什么吗?实际上我不知道怎么做,所以我无法回答你的问题。但是请注意,当你长按home按钮时,并非所有Android手机都有相同的行为。一些人打开应用程序切换器,另一些人打开助手。另外,我想知道您是否可以验证按钮的默认行为。让我们来看看这个问题,在新的Amazon Fire设备上,长时间按下Home按钮会触发Alexa进行监听,这就是我想要通过编程实现的。