Reputation: 643
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
Upvotes: 6
Views: 3788
Reputation: 462
there is finishAffinity()
method that will finish the current activity and all parent activities, but it works only in Android 4.1 or higher
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
}
Upvotes: 7
Reputation: 637
In an app I made, I have put:
if(Globals.isExit){
finish();
}
In every onResume() method in every activity.
Globals is a class that is declared as an in the manifest.xml. The Global class has a boolean called exit.
In all activities option menu, include an exit option thats sets Globals.exit to true, and calls finish()
Then any activities left unfinished are all finished.
Not sure if you would need to use an intent to clear the backstack or if finishing clears it for you. Sorry if im wrong on that bit.
Sorry for any bad typing, I'm on a phone.
Upvotes: -1