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