I have various activities in my app and the flow is very complex. What I want to do is, as soon as usb device is attached, I want to clear and finish the back stack activities, then finish the current activity and the System.exit(0) to close the app.
I have already implemented usb device listener. I want to know how do I clear and finish back stack activities(if there are any, it is not going to have any backstack activities everytime) and then finish the current one.
Also, If my activity A is on Top and it has 2 activities (B,C) in back stack. Now if activity A is running in the background and usb connected, only Activity A will listen to it right? (I have usb receiver implemented in every activity.)
How do I achieve this without my app crash?
Thanks
Use finishAffinity() to clear all backstack with existing one. Suppose, Activities A, B and C are in stack, and finishAffinity(); is called in Activity C, - Activity B will be finished / removing from stack. - Activity A will be finished / removing from stack. - Activity C will finished / removing from stack.
In the second activity, the back button at the top left can be used to go back to the previous activity.
there is finishAffinity()
method that will finish the current activity and all parent activities, but it works only in Android 4.1 or higher
Source
finishAffinity()
will Finish this activity as well as all activities immediately below it in the current task that have the same affinity
If you want for all API levels
in one of your activities
Intent intent = new Intent(this, YourActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // this will clear all the stack
intent.putExtra("Exit me", true);
startActivity(intent);
finish();
Then in YourActivity onCreate() method add this to finish the Activity
setContentView(R.layout.your_layout);
if( getIntent().getBooleanExtra("Exit me", false)){
finish();
return; // add this to prevent from doing unnecessary stuffs
}
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