简体   繁体   中英

finishActivity() not working as intended in Android

Following Scenario:

I got 4 Activities, A, B1, B2, and C

Activity A calls B1 by:

    public void toB1(View view)
    {
       Intent b1 = new Intent(this, B1Activity.class);
       startActivityForResult(b1, 2);
    }

Activity B1 calls B2 by:

    public void toB2(View view)
    {
        Intent b2 = new Intent(this, B2Activity.class);
        startActivity(b2);
    }

Then, when B2 has finished its work it should call C and close B1 and B2 by:

    public void toC(View view)
    {
        Intent c = new Intent(this, CActivity.class);
        finish();
        finishActivity(2);
        startActivity(c);
    }

But now, when being at C and clicking the return key, I get directed to B1 instead of A.

But B1 should be finished, is there an error in my code or do I misunderstand the concept of startActivityForResult ?

I solve it look below for that you have to create Singleton ,

B1Activity.java

 public static B1Activity instance = null; //declare it global

And start intent this way.

 public void onClick(View v) {
                Intent b2 = new Intent(B1Activity.this, B2Activity.class);
                startActivity(b2);
            }

and create this method

 @Override
    public void finish() {
        super.finish();
        instance = null;
    }

Now in B2Activity.java use this code.

public void onClick(View v) {

                Intent c = new Intent(B2Activity.this, CActivity.class);
                if(B1Activity.instance != null){
                    B1Activity.instance.finish();
                }
                B2Activity.this.finish();
                c.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(c);
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM