Skip to content Skip to sidebar Skip to footer

How To Kill Activity B When Coming From Activity C To Activity A In Android

I'm a beginner in android app development. I've developed an app which has 5 Activities: (i.e. Activity - MainActivity, B, C, D, E). when the user opens the app the MainActivity w

Solution 1:

When you click OK in Activity C,D,E which is meant to take you to the main activity while skipping Activity B, then you should specify flag

Intent intent = newIntent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

I think that should work.

If that actually doesn't work (I'd be surprised), a possible alternative is using startActivityForResult() in Activity B, to which you'd write a result handling

Intentintent=newIntent(this, ActivityC.class);
startActivityForResult(intent, 1);

@OverrideprotectedvoidonActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == 1 && resultCode == 1) {
        this.finish();
    }
}

And in Activity C, when you click OK button;

this.setResult(1);
finish();

Solution 2:

you may use:Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP. (For Example)

Intent intent = newIntent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);

To clear all previous activitys(s) and start a new one.

and check if exit=truefinish() the current one.

you can also use:android:noHistory="true" in your activity Tag in the Manifest.xml

Note: this will keep no history it means that after you open another activity the previous one will be killed.

Solution 3:

If you want to clear all activities you can use finishAffinity() if you are targeting 16 and 16+. For below 16 flags

Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP

Can be used. The finishAffinity() will finish all the activity no matter how many are there below in the task stack. if you don't want to have an Activity visible if you comeback from another Activity you can finish it when you start the another.

Post a Comment for "How To Kill Activity B When Coming From Activity C To Activity A In Android"