Some one Some where
Some one Some where

Reputation: 777

Handling Activity Stack in Android, am I leaking Memory with My approach.?

I have 4 Different Activities, and going through the links I have created a Sample for the same.

Objective:

Activities A,B,C,D;

A -> B -> C -> D

An event in D causes C and D to pop Leaving A and B in stack.

An event in D may cause B C and D to POP leaving only A in stack.

Implementation:

I use the following Event for my First Three Activities i.e. A B C

if(v==buttonNext){
        Intent secondAct=new Intent(FirstActivity.this, SecondActivity.class);
        //storing the Stack
         MaintainMyStack.addBackActivity(this); 
        startActivity(secondAct);
    }

I use the following Event for my Forth Act. i.e. D

if(v==btnBack){
        finish();//finishes  "D"
        Activity act=MaintainMyStack.getBackActivity();

        act.finish(); //finishes last in stack i.e. "C"
    }

I use this Common Class Amongst My A B C D Activities.

public class MaintainMyStack  {
    private static Stack<Activity> classes = new Stack<Activity>();

    public static Activity getBackActivity() {
    return classes.pop();
    }
    public static void addBackActivity(Activity c) {
    classes.push(c);
    }
}

It works as desired, but I am just concerned about the MaintainMyStack class might Leak Memory when it meets real Scenerio, Please suggest should I go with this approach or Do we have other options to implement the same. How can i create the MaintainMyStack have just one instance without leaking any memory

Upvotes: 0

Views: 178

Answers (2)

Ani
Ani

Reputation: 1621

If you use this then no need to maintain you stack yourself.

Intent intent = new Intent(FourthActivity.this,MainActivity.class);
intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
FourthActivity.this.startActivity(intent);

You can use FLAG_ACTIVITY_CLEAR_TOP but sometimes it wont work.Sometimes it pops only top activity.

Upvotes: 1

Ovidiu Latcu
Ovidiu Latcu

Reputation: 72311

You should have a look at the Intents flag FLAG_ACTIVITY_CLEAR_TOP. Adding this flag to your Intent will do exactly what you are trying to achieve with your own activity stack, and you won't need that anymore.

Upvotes: 1

Related Questions