Android的,如何接收home键点击通过广播接收器?接收器、Android、home

2023-09-07 01:56:10 作者:只有公主病没有公主命

在我的应用程序需要通过单击注销按钮或关闭应用程序由pressing home键键当过用户外出应用程序发送注销请求到服务器。

In my application I need to send log-out request to server when ever user goes out of application via clicking on log-out button or closing application by pressing home button key.

有一个与按钮,结果没有问题,因为我期望的那样。现在的问题是如何回家按钮。根据我的研究,不可能使用的onkeydown(INT键code,KeyEvent的事件),因为我们可以用获取的后退按钮。

There is no problem with button and result is as I expect. The problem is how to get home button. Based on my research it is not possible to use onKeyDown(int keyCode, KeyEvent event) as we can use for getting back button.

这是我想的是注册一个接收器和发送广播,只要Home键点击的解决方案。因此,通过接收器,我可以推出一个服务来发送注销请求给服务器。

The solution that I'm thinking about is registering a receiver and sending a broadcast whenever Home button clicked. So through receiver I can launch a service to send log-out request to server.

我现在的问题是,我不能回家按钮,每当我点击它。这一点,我已经写了code:

My current problem is I cannot get home button whenever i click it. This the code that I have written:

的manifest.xml

<application ...

        <receiver android:name="HomeButtonReceiver" >
            <intent-filter>
                <category android:name="android.intent.category.HOME" />
            </intent-filter>
        </receiver>

</application>

HomeButtonReceiver

public class HomeButtonReceiver extends BroadcastReceiver {

    private final String TAG = "HomeButtonReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(TAG, "inside onReceive()...");
    }
}

任何意见/建议将是AP preciated。 谢谢

Any comments/suggestions would be appreciated. Thanks

推荐答案

你为什么不使用 dispatchKeyEvent 功能。它可以拦截HOME键pressing事件。

Why dont you use dispatchKeyEvent function. It can intercept the HOME button pressing event.

@Override
    public boolean dispatchKeyEvent(KeyEvent keyevent) {

        if (keyevent.getKeyCode() == KeyEvent.KEYCODE_HOME) {
            //Do here what you want
            return true;
        }
        else
            return super.dispatchKeyEvent(event);
   }