Close app in onBackPressed()'s MainActivity

1.1k views Asked by At

I want my app to close when I press the back button on MainActivity. Currently when I press it on MainActivity, it returns to previous activity.

3

There are 3 answers

0
Anthony On
@Override
public void onBackPressed() {
   YourActivity.this.finish();       
}

It's worth noting that changing the default behavior is not a good idea.

0
V.Sch On

You can use System.exit(0).

    @Override
    public void onBackPressed() {
        System.exit(0);
    }
0
Slagathor On

Why would you want your app to not go back to previous activities? If your MainActivity is started by an activity you don't want to go back to, its better to add flags to the intent that started MainActivity so the previous activity would not stay in the Task-stack.

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

If you dont want to do that, you must override the OnBackPress() to remove/finish the Tasks under the MainActivity in the stack. This can be done with a LocalBroadcaster for example, even though its quite ugly.

In the activity you want to close:

BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        finish();
    }
};

@Override
protected void onResume() {
    super.onResume();
    IntentFilter filter = new IntentFilter("Your filter");        
    LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, filter);
 }

@Override
protected void onDestroy() {
    super.onDestroy();
    LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
}

In your MainActivity:

@Override
public void onBackPressed() {
    Intent intentBroadcast = new Intent("Your filter");
    LocalBroadcastManager.getInstance(MainActivity.this).sendBroadcast(intentBroadcast);
    finish();
}