How do I close an Android app on onBackPressed?
I have three screens (actions). Let's say A, B, C.
The screen transition occurs in the order A, B, C.
I want to close the application as soon as the user clicks the back button from the third screen (screen C).
How to do it?
try the following code in c button "back" press button
System.exit(0);
or you can also use the following code
android.os.Process.killProcess(android.os.Process.myPid());
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();
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.
Use the following intent when opening Activity C from Activity B,
Intent intent = new Intent(this, StartActivity.class)
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
It will complete all previous steps.
When you start activity C from activity B use this code to start your activity. C:
Intent intent = new Intent(getApplicationContext(), ActivityC.class)
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Hope this helps you.