I want to kill the app when user presses the home button. Is there any way to do this on Android?
6 Answers
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

- 5,147
- 2
- 25
- 21
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.

- 6,011
- 1
- 36
- 31
-
Sorry I did'nt see your answer :-) – Bourbon Jan 16 '12 at 10:00

- 13,423
- 6
- 32
- 45
-
This method just finishes the activity. However I want to finish the application. – ipman Jan 16 '12 at 09:43
-
if pressing home is taking you back on home screen then its automatically finishing the application too, unless you are not running a service besides your activity with in the same application – waqaslam Jan 16 '12 at 09:46
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/

- 1,035
- 7
- 19
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
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.

- 1,572
- 13
- 24
-
3KeyEvent.KEYCODE_HOME is never forwarded to applications but handled by system. – harism Jan 16 '12 at 09:52
-
-