Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I close my application on back pressed in android

Tags:

android

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;
}
like image 593
user1061793 Avatar asked Nov 28 '22 04:11

user1061793


2 Answers

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.

like image 96
Squonk Avatar answered Dec 09 '22 17:12

Squonk


You can try this

@Override
public void onBackPressed() {
        Intent startMain = new Intent(Intent.ACTION_MAIN);      
        startMain.addCategory(Intent.CATEGORY_HOME);                        
        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);          
        startActivity(startMain); 
  }
like image 33
Bunny Avatar answered Dec 09 '22 17:12

Bunny