Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop startActivity from making two instances of the same Activity

Activity A has a button and in its onclick it starts new activity B, the new activity only has minimal onCreate function.

In activity A I push a button which uses

startActivity(new Intent(A.this, B.class)) 

to start activity B. when I run the program, push the button in activity A, activity B starts but I have to use back button twice to exit and get back to the first activity.

I checked the logcat when the button in A is clicked, two same instances are made simultaneously. Also I tried using Toast in onCreate in Activity B for debugging, which shows that when I use back button it calls the onCreate in the other twin B Activity. I found this post Clicking the back button twice to exit an activity which does not answer the question.

The only way that I could stop it from making twin instances was by explicitly limiting it using the tag:launchMode= "singleInstance" to the activity in manifest.

The questions still remain:

  1. why it makes two instances?
  2. How to stop it or how to use it correctly so that this wont happen?

More explanation: The code: Activity A has a buttOnClick() function in which there is a switch(view.getId()) that checks which button was clicked. each case calls function animation with a specific integer parameter (button id). in this function again switch checks the id and runs the animation corresponding to the button using setAnimationListener.At the end of the animation it asks for starting a new activity. Here is what it looks like:

public void myButtonOnClick(View view)
    {


        switch (view.getId()) {

        case R.id.button1:

            animation(1);

            break;
           //....more lines.....  }}
public void animation(int a){

           //...code...

          switch(a){

        case 1:
            anim.setAnimationListener(new AnimationListener() {

                public void onAnimationStart(Animation arg0) {
                    // TODO Auto-generated method stub

                }

                public void onAnimationRepeat(Animation arg0) {
                    // TODO Auto-generated method stub

                }

                public void onAnimationEnd(Animation arg0) {
                    Intent in =new Intent(A.this,     B.class);
                    startActivity(in.addFlags(      Intent.FLAG_ACTIVITY_CLEAR_TOP ));
                    animClear();
                }
            });


            break;
//......... other cases......}
like image 678
yav dat Avatar asked Dec 28 '12 23:12

yav dat


1 Answers

Intent flags

I myself used a set of FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_RESET_TASK_IF_NEEDED but that might be an overkill.

Then just

startActivity(new Intent(A.this, B.class).addFlags(intent_flags));
like image 72
aragaer Avatar answered Oct 02 '22 22:10

aragaer