Reputation: 1222
I want to kill the app when user presses the home button. Is there any way to do this on Android?
Upvotes: 2
Views: 3250
Reputation: 1592
JoxTraex answer is right but maybe specify that you can capture home button to be able to execute finish on the activity you want:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if (keyCode == KeyEvent.KEYCODE_HOME) {
finish();
}
}
Comments are right, I just tried with KeyEvent.KEYCODE_BACK sorry! Then I would try overwriting onStart() and onStop() functions for each activity to know when there is no more activities opened on my app.
Upvotes: -2
Reputation: 6073
I implemented something similar by overriding Activity.onUserLeaveHint()
. This method gets called once home key is pressed but I think there where some caveats I can't remember right now. Namely it got called on situations I didn't want my application to finish and had to put flags to prevent unwanted exits.
Upvotes: 1
Reputation: 8612
If you don't write your own home app - do not provide any special action for home or back buttons. Read this question and answer for good explanation why you don't need this
Upvotes: 0
Reputation: 1065
You can try this :
@Override
public void onUserLeaveHint() {
finish();
}
You will find more details here :
http://tech.chitgoks.com/2011/09/05/how-to-override-back-home-button-in-an-android-app/
Upvotes: 0
Reputation: 5177
when pressed Home, your app will hiden and will invoke onStop
method, so you can invoke finish
in the onStop
method.
But if another application be front of your app, also your app will hide, so can not identify Home pressed or another application rightly, so suggestion use follow:
static final String SYSTEM_DIALOG_REASON_KEY = "reason";
static final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
static final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
static final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (reason != null) {
Lg.i("receive action:" + action + ",reason:" + reason);
if (mListener != null) {
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
mListener.onHomePressed();
} else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
mListener.onHomeLongPressed();
}
}
}
}
}
}
here is a complement code HomeWatcher
Upvotes: 2