How can I close my application on back pressed in android

后端 未结 12 1274
轻奢々
轻奢々 2021-01-14 00:04

I want to go on home screen when I press device\'s back button.I am using this code..

public void onBackPressed() {
   this.finish();
   return;
}

12条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-14 00:29

    Pressing the BACK key will effectively call finish() for you. There is no need to trap the BACK key.

    I'm assuming your problem is that when you press the BACK key it is simply going back to the previous Activity in your app.

    If that is the case then make all activities 'self-terminate' when they start a new Activity in your app....

    startActivity(new Intent(this, MyNewActivity.class));
    finish();
    

    If you do that then there will be no Activity to return to when you press BACK and it will always return to the home screen.

提交回复
热议问题