0

I just want to exit the app completely when user press home, or switch to other app. Is there any event I can listen so that I can do the exit code?

Bin Chen
  • 58,165
  • 53
  • 139
  • 181

3 Answers3

0

When Home key is pressed you handle like this :

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_HOME) {
        finish();
    }
    return false;
}
Tarsem Singh
  • 13,979
  • 7
  • 50
  • 70
0

Try this it works fine with me

// clear whole activity stack

    Intent intent = new Intent("clearStackActivity");
    intent.setType("text/plain");
    sendBroadcast(intent);

// start your new activity
Intent intent = new Intent(OrderComplete.this,
                    MainActivity.class);
startActivity(intent);

Put these line in onCreate() method of all Activities or if you have any base activity you can put it there , then no need to put in all activities.

private KillReceiver clearActivityStack;
clearActivityStack = new KillReceiver();
        registerReceiver(clearActivityStack, IntentFilter.create("clearStackActivity", "text/plain"));

put this class in your Base activity

private final class KillReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    }
Biraj Zalavadia
  • 27,812
  • 10
  • 59
  • 76
0

I found this from here.

Override below method in your activity.

@Override
public void onAttachedToWindow() {
    super.onAttachedToWindow();
    this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);           
}

After overriding above method, now you can easily listen HOME Key press in your activity using onKeyDown() method.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {     

    if(keyCode == KeyEvent.KEYCODE_HOME)
    {
       //The Code Want to Perform. 
    }
});
Bishan
  • 14,610
  • 50
  • 157
  • 245
  • from the link u mention, it only works prior 4.0.3 I think it is a "bug" actually as google don't intend to let u capture home button anyway :) – Bear Sep 09 '13 at 09:29