Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Clear all backstack activities and then finish current activity

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

like image 329
dhun Avatar asked Apr 10 '15 18:04

dhun


People also ask

How do I delete my Backstack activity?

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.

How do I go back to previous activity on Android?

In the second activity, the back button at the top left can be used to go back to the previous activity.


1 Answers

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
}
like image 150
Sai Phani Avatar answered Oct 14 '22 22:10

Sai Phani