Amit Tiwari
Amit Tiwari

Reputation: 3692

Conditionally clear activity backstack

I am working on an app on which you can share images from your local phone's gallery app. Whenever a photo is shared through the gallery app, an Activity A opens up in my app.

The photo sharing follows some steps in which it goes from Activity A to Activity B and the final step in B opens the Main Activity.

What I want, pressing back from B should open A. Pressing the final button in B should clear both A and B from backstack, so that if you press back on Main Activity, the app should close.

What I did :

  1. Initially, I was opening Main Activity with this flag intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); But, this started a new task and so even when I used to close my app and go to the phone's gallery app, it would show A instead of the photo on that app, when you pressed back, then you could see the actual image in that gallery app.

  2. I had specified android:noHistory="true" for A and B and started the intent to Main Activity without the new task flag. This solved the new task problem in the sense that when I close my app and switched back to the gallery app, it showed the actual image not my activity A. But the issue here is, I can't go back to A from B, also if the app is minimised, then also the activity is gone.

Upvotes: 0

Views: 119

Answers (2)

yao liu
yao liu

Reputation: 121

Create a singleton class :

Stack<Activity> stack;

public void add(Activity activity){
   stack.add(activity).
}

public void remove(){
   Activity activity = stack.lastElement();
   if(activity != null) {
      stack.remove(activity).
      activity.finish();
   }
}

public void removeAll() {
   for (Activity activity : stack) {
      if (activity != null)
         activity.finish();
   }
   stack.clear();
}


call add() in your activities' onCreate()
call remove will finish current activity
call removeAll will finish all activities added into the stack

Upvotes: 1

Abhishek
Abhishek

Reputation: 1674

 Intent l = new Intent(getApplicationContext(), MainActivity.class);
                        l.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                        l.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        l.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        finish();
                        startActivity(l);

use this on finish button in avtivity B.

Upvotes: 0

Related Questions