Finish parent and current activity in Android

You shou use onActivityResult method in your parent Activity

Suppose Activity A is parent of Activity B. If you want to click back button in Activity B to exit Application (also exit Activity A)

In your Activity B, in onStop() or onDestroy()

you call

setResult(0); //any int number is fine

this will pass a result code to its parent activity.

Your parent Actvity A, listens for the result code you will need to use onActivityResult method inside the method you can call

if(resultCode == 0) //matches the result code passed from B
{
    ActivityA.this.finish()
}

It works for me :)


None of that worked for me. So I found out a solution. The help clearly lists that Intent.FLAG_ACTIVITY_CLEAR_TASK must be used with Intent.FLAG_ACTIVITY_NEW_TASK. So here is a code that worked for me.

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

I don't know if this will work, but you could try it:

  • From Activity A, start activity B for a result using startActivityForResult()

  • In Activity B, when the user triggers Activity C, start activity C.

startActivity() returns immediately, so

  • set a result that will inform A to finish as well,

  • Call finish() in B.

  • When A receives that result from B, A calls finish() on itself as well.

Failing that, you could make Activity C into its own app and then close the first app (with A & B) after it starts the second.

P.S. Take Falmarri's comment into consideration as you move forward!
Good luck.


If you want to finish a parent activity from a child activity,

In the parent activity, while triggering the child activity, use the following command:-

startActivityForResult(intent_name,any_integer_variable);

and override the onActivityResult Method in the following manner:-

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(resultCode==2){
        finish();
    }
}

Now, in the child activity, override onStop and onDestroy in the following manner:-

protected void onStop() {
    setResult(2);
    super.onStop();
}
@Override
protected void onDestroy() {
    setResult(2);
    super.onDestroy();
}

Notice that I've set the value to 2 in the child activity, and am checking for it in the parent activity. If the value is the same that I have set, then the parent activity will also finish. Then you can use recursive approaches for further activities.