My application has the following flow:
Home->screen 1->screen 2->screen 3->screen 4->screen 5>Home->screen 2->Home->Screen 3
My problem is that when I am trying to close the application then Home activity opens everytime when I am trying to close the application.
I just want to close the application when user presses the back key of device on home screen.
There is finishAffinity() method that will finish the current activity and all parent activities, but it works only in Android 4.1 or higher.
This works well for me.
You should using FLAG_ACTIVITY_CLEAR_TASK
and FLAG_ACTIVITY_NEW_TASK
flags.
Intent intent = new Intent(SecondActivity.this, CloseActivity.class);
//Clear all activities and start new task
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
onCreate()
method of CloseActivity
activity.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
finish(); // Exit
}
Use finishAffinity()
method that will finish the current activity and all parent activities. But it works only for API 16+
mean Android 4.1 or higher.
API 16+ use:
finishAffinity();
Below API 16 use:
ActivityCompat.finishAffinity(this); //with v4 support library
To exit whole app:
finishAffinity(); // Close all activites
System.exit(0); // Releasing resources
Sometime finish()
not working
I have solved that issue with
finishAffinity()
Do not use
System.exit(0);
It will finish app without annimation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With