How do I close an Android app on onBackPressed?
5 answers
As suggested by user 936414, when you go from activity A to B, you end activity A, when you go from activity B to C, you end activity B, so when you reach activity C, this will be the only activity on the stack and throwing back will close it.
Like this:
startActivity(new Intent(getApplicationContext(), NextActivity.class));
finish();
+3
source to share
You can register the next broadcast receiver in each event
/* Logout Intent Actions */
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.package.ACTION_LOGOUT");
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("MyApp","Loggin out from <activity>");
finish();
}
};
registerReceiver(broadcastReceiver, intentFilter);
/* Logout Intent Actions */
And then on each you just call
broadcastIntent.setAction("com.package.ACTION_LOGOUT");
sendBroadcast(broadcastIntent);
This will send a broadcast to close all activity and put the app in the background.
Remember that the concept of "closing an application" is completely different in Android because you cannot actually stop it.
+1
source to share