Android, How to receive home button click through broadcast receiver?

▼魔方 西西 提交于 2019-12-01 11:22:43

问题


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.

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.

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.

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()...");
    }
}

Any comments/suggestions would be appreciated. Thanks


回答1:


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



回答2:


What you can do is like this

Create your Home button event catcher

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(keyCode==KeyEvent.KEYCODE_HOME){
       //Send your own custom broadcast message
    }
    return super.onKeyDown(keyCode, event);
}

Now you can create a broadcast receiver so that you can receive your message

You can refer here and here for how to send a broadcast messsage




回答3:


If you just need to find out when ever the user goes out of application , why don't you use the onPause(..) method of the Activity?



来源:https://stackoverflow.com/questions/13302167/android-how-to-receive-home-button-click-through-broadcast-receiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!