Finish parent and current activity in Android

AndroidAndroid Activity

Android Problem Overview


I have 3 activities. Activity A which leads to activity B, which in turn can go back to activity A or start activity C. However, if I press back in activity C the app should close.

To sum up:

  • Activity A starts activity B
  • Pressing Back on activity B should lead to A
  • Activity B starts activity C
  • Pressing Back on activity C should close the app

How should I go from activity B to C? This code currently gives me a NullPointerException on the last line:

Intent intent=new Intent(ActivityB.this, ActivityC.class);
startActivity(intent);
ActivityB.this.finish();
ActivityB.this.getParent().finish();

If I switch the last two lines I also get a null pointer.

Android Solutions


Solution 1 - Android

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.

Solution 2 - Android

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.

Solution 3 - 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 :)

Solution 4 - Android

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);

Solution 5 - Android

I didn't do any of this. This is how I would revise your code.

the code you use to enter another intent:

Intent whatEverIntentName = new Intent("Path.to.next.Intent");
startActivity(whatEverIntentName);
finish();

This way, you always quit when pressing back. But wait! You can change how you want your back key press to react when pressed.

Do this:

@Override
public void onBackPressed() {
	super.onBackPressed();
	Intent whatEverIntentName = new Intent("Path.to.the.activity.before.it");
	startActivity(whatEverIntentName);
// Don't add finish here. 
//This is necessary because you finished your last activity with finish();
}

Solution 6 - Android

You can use finishAffinity() , it will close Current & all Parent Activities of the Current Activity.

Note : But any results from Child Activity to Parent Activity will not be handled.

Hope, it helps !!

Solution 7 - Android

try this

  Intent intent = new Intent(Intent.ACTION_MAIN);
  intent.addCategory(Intent.CATEGORY_HOME);
  intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  startActivity(intent);				

Solution 8 - Android

if you are on Activity A and started another activity called Activity B. Activity A --> Activity B

And now want to close both activities.

then use the below code in Activity B.

B.this.finish();

And use this code in Activity A:

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

As soon as activity B will finish, Activity A will also finish.

There is one drawback, I do not know may be you want this or not.

Drawback is that If user is on Activity B and s/he press back button to move on the Activity A. Then, Activity A will also finish in this case.

Solution 9 - Android

This is working perfectly:

btn_back.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
			
Player.this.finish();
	}
});

Solution 10 - Android

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

your activity C will the root activity and on press back will finish the apps.

Solution 11 - Android

From the screen(B) you want to start the screen(C) with NO back screen, just start this screen (C) with:

screenC.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP 
    | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(screenC);
finish();

The back in screenC will exit the application.

Solution 12 - Android

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

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. and Call setResult() method before finish() method in your Child Activity In Parent Activity overide onActivtyResult(....) method. When A receives that result from B, A calls finish() on itself as well.

enter code here
     @Override
protected void onActivityResult(int arg0, int arg1, Intent arg2) {
	//Added by Ashish to close parent activity
	  if(arg1==19){
	  finish();
	    }
	super.onActivityResult(arg0, arg1, arg2);
}

Solution 13 - Android

Have each activity listen for a result from the next activity, and finish itself if that occurs.

You can use a special result code to indicate that you want the activity to finish.

Solution 14 - Android

You can just override the back key behavior:

> Activity A starts activity B
> Pressing Back on activity B should lead to A
> Activity B starts activity C
> Pressing Back on activity C should close the app

Note that I don't call super from onBackPressed. This also allows you to override the browse stack mechanism for Android, which I find to be a big advantage, since currently there doesn't seem to be a way to clear the single oldest item from the browse stack in a simple way.

public class B extends Activity
{
    ...
    @Override
    public void onBackPressed()
    {
        // Start activity A
        Intent aIntent = new Intent(this, A);
        startActivity(bIntent);
    }
    ...
}

public class C extends Activity
{
    ...
    @Override
    public void onBackPressed()
    {
        // Close
        finish();
    }
    ...
}

You can specifically finish the parent activity if needed too, but using this method, you don't have to worry about it.

Solution 15 - Android

The following code should do it for you. Almost in all other approaches your app will remain in recent apps. Javadoc can be found at, https://developer.android.com/reference/android/app/ActivityManager.AppTask.html#finishAndRemoveTask()

            ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
            if(am != null) {
                List<ActivityManager.AppTask> tasks = am.getAppTasks();
                if (tasks != null) {
                    tasks.get(0).finishAndRemoveTask();
                }
            }

Solution 16 - Android

Create instance of ActivityB.

on ActivityB.java

public static ActivityB instanceOfActivityB;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    instanceOfActivityB = this;
}

on ActivityC.java

void onClose() {
   ActivityB.instanceOfActivityB.finish();
   finish();
}

Hope it helps!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhpiqueView Question on Stackoverflow
Solution 1 - AndroidcodinguserView Answer on Stackoverflow
Solution 2 - AndroidAnuj AgarwalView Answer on Stackoverflow
Solution 3 - AndroidTS.xyView Answer on Stackoverflow
Solution 4 - AndroidYugankView Answer on Stackoverflow
Solution 5 - AndroidLifesAwayView Answer on Stackoverflow
Solution 6 - AndroidAnimesh ManglaView Answer on Stackoverflow
Solution 7 - AndroidKetan AhirView Answer on Stackoverflow
Solution 8 - AndroidAli ShanView Answer on Stackoverflow
Solution 9 - AndroiddhrupalView Answer on Stackoverflow
Solution 10 - AndroidVipin SahuView Answer on Stackoverflow
Solution 11 - AndroidmiroslavignView Answer on Stackoverflow
Solution 12 - AndroidAshish SainiView Answer on Stackoverflow
Solution 13 - AndroidCheryl SimonView Answer on Stackoverflow
Solution 14 - AndroidPeter AjtaiView Answer on Stackoverflow
Solution 15 - AndroidHamzeen HameemView Answer on Stackoverflow
Solution 16 - AndroidTrần Thị Diệu MyView Answer on Stackoverflow