假的 KeyEvent 并不像“真实”的那样“完全”工作。按钮。为什么?

发布于 2024-11-03 08:48:59 字数 580 浏览 6 评论 0原文

我试图用 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);

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

为什么?

I am trying to invoke my main activity's onKeyDown() with KEYCODE_BACK, so that it behaves as if I pressed the 'back' button myself. I do that using the following code:

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

My activity's onKeyDown() currently only calls:

return super.onKeyDown(keyCode, event);

Yet, unlike the real Back button, when the "fake" code is called, the activity refuses to become invisible.

Why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

月牙弯弯 2024-11-10 08:48:59

使用

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

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

use

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

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

挽清梦 2024-11-10 08:48:59

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

Aleadam method don't work on my android 4.1.2. So I write workaround:

public void dispachBackKey() {
    dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
    dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
}
习ぎ惯性依靠 2024-11-10 08:48:59

尝试使用这个

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

Try using this

public boolean onKeyDown(int keyCode, KeyEvent event) 
{
    if (keyCode == KeyEvent.KEYCODE_BACK) 
    {
        //....
    }
    return true;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文