假冒KeyEvent不能正常工作*就像“真实”按钮一样。为什么?

时间:2011-04-22 01:27:57

标签: android back-button keyevent onkeydown onpause

我试图用KEYCODE_BACK调用我的主要活动的onKeyDown(),这样它就像我自己按下“后退”按钮一样。我使用以下代码执行此操作:

   KeyEvent goBackDown = new KeyEvent(0,0,KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_BACK,0,0);
    goBackDown.dispatch(activity);
    SystemClock.sleep(50);  // as if human pressed the key
    KeyEvent goBackUp = new KeyEvent(0,0,KeyEvent.ACTION_UP,KeyEvent.KEYCODE_BACK,0,0);
    goBackUp.dispatch(activity);

我的活动的onKeyDown()目前只调用:

return super.onKeyDown(keyCode, event);

然而,与真实后退按钮不同,当调用“假”代码时,活动拒绝变为不可见。

为什么?

3 个答案:

答案 0 :(得分:11)

使用

dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_BACK));

http://developer.android.com/reference/android/view/View.html#dispatchKeyEvent%28android.view.KeyEvent%29

答案 1 :(得分:3)

Aleadam方法在我的Android 4.1.2上不起作用。所以我写了解决方法:

public void dispachBackKey() {
    dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
    dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
}

答案 2 :(得分:2)

尝试使用此

public boolean onKeyDown(int keyCode, KeyEvent event) 
{
    if (keyCode == KeyEvent.KEYCODE_BACK) 
    {
        //....
    }
    return true;
}