73

I have an application with multiple pages i.e., multiple activities and some of them remain open.

Is there a way to close all activities at once?

Jonathan Soifer
  • 2,715
  • 6
  • 27
  • 50
steve
  • 1,365
  • 4
  • 19
  • 33
  • 1
    Can you describe in more detail your app / scenario? Closing all activities at once isn't usually needed. – fhucho Dec 22 '12 at 10:41

21 Answers21

136

Whenever you wish to exit all open activities, you should press a button which loads the first Activity that runs when your application starts then clear all the other activities, then have the last remaining activity finish. to do so apply the following code in ur project

Intent intent = new Intent(getApplicationContext(), FirstActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);

The above code finishes all the activities except for FirstActivity. Then we need to finish the FirstActivity's Enter the below code in Firstactivity's oncreate

if (getIntent().getBooleanExtra("EXIT", false)) {
    finish();
}

and you are done....

hasan
  • 23,815
  • 10
  • 63
  • 101
letsnurture
  • 2,193
  • 1
  • 17
  • 20
  • 1
    but this code, it will make your "Back" button no longer working as usual. It will close everything when you click "Back" button. So how to deal with that / @letsnurture ? – gumuruh Jul 13 '14 at 05:37
  • What does `putExtra` do? – User Nov 27 '14 at 18:14
  • 1
    @letsnurture activity will remain in recent apps list – Erum Feb 20 '15 at 12:07
  • 1
    What can do while launching form Receiver. I tried same you suggest but it's not working...any suggestion? – CoDe Apr 06 '15 at 10:17
  • did not work, still has an activity which has not been destroyed – Jemshit Oct 05 '15 at 14:55
  • @Jemshit Iskenderov aren't destroyed because you need preserve sessions objects etc. if you want stop system(0) you can see in google. –  Dec 11 '15 at 13:39
  • getIntent() will not work in Oncreate, because your FirstActivity is already created. So use onNewIntent(Intent data), it will help you to get intent on FirstActivity..... – Narender Gusain Feb 02 '16 at 13:41
  • Need return after finish(), else u will get a looping start activity : if (getIntent().getBooleanExtra("EXIT", false)) { finish(); return; } – Chris Ho Jun 02 '16 at 02:26
  • Shouldn't this more ideally be handled in `FirstActivity`'s `onNewIntent`? – Veneet Reddy May 08 '17 at 11:15
  • + must check getIntent().getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY == 0, otherwise if launch app from recents, App finish() it self, because Intent.extra."EXIT" remains in Intent – StepanM Mar 30 '18 at 12:32
  • 3
    Intent intent = new Intent(getApplicationContext(), LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); – Dante Jun 05 '18 at 08:14
80

There is a finishAffinity() method in Activity that will finish the current activity and all parent activities, but it works only in Android 4.1 or higher.

For API 16+, use

finishAffinity();

For lower (Android 4.1 lower), use

ActivityCompat.finishAffinity(YourActivity.this);
King of Masses
  • 18,405
  • 4
  • 60
  • 77
  • 4
    For older versions of Android, use [`ActivityCompat#finishAffinity()`](https://developer.android.com/reference/android/support/v4/app/ActivityCompat.html#finishAffinity(android.app.Activity)). – Pang Oct 26 '16 at 10:15
24

The best solution i have found, which is compatible with devices having API level <11

Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
ComponentName cn = intent.getComponent();
Intent mainIntent = IntentCompat.makeRestartActivityTask(cn);
startActivity(mainIntent);

This solution requires Android support library

Vishal Yadav
  • 3,642
  • 3
  • 25
  • 42
Mongi Zaidi
  • 1,043
  • 10
  • 15
22

For API 16+, use

finishAffinity();

For lower, use

ActivityCompat.finishAffinity(YourActivity.this)
Radu Grigoras
  • 229
  • 2
  • 4
  • 1
    May I request you to please add some more context around your answer. Code-only answers are difficult to understand. It will help the asker and future readers both if you can add more information in your post. – RBT Jan 20 '17 at 00:25
11

There are three solution for clear activity history.

1) You can write finish() at the time of start new activity through intent.

2) Write android:noHistory="true" in all <activity> tag in Androidmanifest.xml file, using this if you are open new activity and you don't write finish() at that time previous activity is always finished, after write your activity look like this.

<activity
    android:name=".Splash_Screen_Activity"
    android:label="@string/app_name"
    android:noHistory="true">

</activity>

3) write system.exit(0) for exit from the application.

Dipak Keshariya
  • 22,193
  • 18
  • 76
  • 128
  • 2
    system.exit(0) for exit from the application : perfect for close Activity from Broadcastreceiver – Akarsh M Jul 15 '14 at 13:57
  • But this will cause not to add activity history to stack , which will cause to restart activity each time put it in to background to foreground – Mr.G Jan 18 '19 at 05:41
11

You can Use finishAffinity() method that will finish the current activity and all parent activities. But it works only for API 16+.

API 16+ use:

finishAffinity();

Below API 16 use:

ActivityCompat.finishAffinity(this); //with v4 support library

To exit whole app:

finishAffinity(); // Close all activites
System.exit(0);  // closing files, releasing resources
Sheikh Hasib
  • 7,423
  • 2
  • 25
  • 37
  • Please don't post identical answers to multiple questions. Post one good answer, then vote/flag to close the other questions as duplicates. If the question is not a duplicate, *tailor your answers to the question.* – Paul Roub Jun 02 '18 at 21:44
  • 1
    thank you sir for help me to sort out this. – MEGHA DOBARIYA Sep 07 '21 at 07:08
9

I was struggling with the same problem. Opening the about page and calling finish(); from there wasn't closing the app instead was going to previous activity and I wanted to close the app from the about page itself.

This is the code which worked for me:

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

Hope this helps.

Abhishek Balani
  • 3,827
  • 2
  • 24
  • 34
9

Following two flags worked for me. They will clear all the previous activities and start a new one

  Intent intent = new Intent(getApplicationContext(), MyDetails.class);
  intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  startActivity(intent);

Hope this helps.

Ajji
  • 3,068
  • 2
  • 30
  • 31
8

None of the other answers worked for me. But I researched some more and finally got the answer.

You actually asked to close the app as I needed. So, add following code:

finishAffinity();
halfer
  • 19,824
  • 17
  • 99
  • 186
Himanshu Sharma
  • 133
  • 2
  • 8
4

If you're looking for a solution that seems to be more "by the book" and methodologically designed (using a BroadcastReceiver), you better have a look at the following link: http://www.hrupin.com/2011/10/how-to-finish-all-activities-in-your-android-application-through-simple-call.

A slight change is required in the proposed implementation that appears in that link - you should use the sendStickyBroadcast(Intent) method (don't forget to add the BROADCAST_STICKY permission to your manifest) rather than sendBroadcast(Intent), in order to enable your paused activities to be able to receive the broadcast and process it, and this means that you should also remove that sticky broadcast while restarting your application by calling the removeStickyBroadcast(Intent) method in your opening Activity's onCreate() method.

Although the above mentioned startActivity(...) based solutions, at first glance - seem to be very nice, elegant, short, fast and easy to implement - they feel a bit "wrong" (to start an activity - with all the possible overhead and resources that may be required and involved in it, just in order to kill it?...)

4

You can try just finishAffinity() , its close all current activities to works on above v4.1

4

Problem with finishAffinity() is that only activities in your current task are closed, but activities with singleInstance launchMode and in other tasks are still opened and brought to the foreground after finishAffinity(). The problem with System.exit(0) is that you finish your App process with all background services and all allocated memory and this can lead to undesired side effects (e.g. not receiving notifications anymore).

Here are other two alternatives that solve both problems:

  1. Use ActivityLifecycleCallbacks in you app class to register created activities and close them when needed: https://gist.github.com/sebaslogen/5006ec133243379d293f9d6221100ddb#file-myandroidapplication-kt-L10
  2. In testing you can use ActivityLifecycleMonitorRegistry: https://github.com/sebaslogen/CleanGUITestArchitecture/blob/master/app/src/androidTest/java/com/neoranga55/cleanguitestarchitecture/util/ActivityFinisher.java#L15
Sebas LG
  • 1,715
  • 1
  • 18
  • 31
1

You can store a boolean flag to represent if all activities should be finished or not (more preferred in your shared preferences) then onStart() method of each activity should have something like:

SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(this);
boolean needToDestroyFlag=pref.getBoolean("destroyFlag", false);
if(needToDestroyFlag)
{
    finish();
}else
{
    //...
}

Obviously you can set this flag like below when ever you need to finish all activities (in the current activity) after doing so you can call finish() method on current activity that will result to terminate current activity and pop activities from stack up one by one, the onStart() method of each one executes and causes to terminate it:

SharedPreferences.Editor editor=PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean("destroyFlag", true);
editor.apply();

If you use the method that @letsnurture suggested, you'll be faced with the question asked by @gumuruh.

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Dmila Ram
  • 1,054
  • 1
  • 13
  • 19
  • Thanks for your approach, it helped me. I did something similar using a static class variable instead of shared prefs, which survives the entire app lifespan. In each activity's onResume, call super.onResume(); if (ExitHelper.isExitFlagRaised) { this.finish(); }. While it might not finish ALL activities, It does finish activities that would be resumed automatically. – Kevin Lee Feb 03 '16 at 09:03
1

Use

finishAffinity ();

Instead of:

System.exit(); or finish();

it exit full application or all activity.

1

You can use the following code:

Intent i = new Intent(OldActivity.this, NewActivity.class);

i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

startActivity(i);
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Enad
  • 21
  • 5
0

If rooted:

Runtime.getRuntime().exec("su -c service call activity 42 s16 com.example.your_app");
gsamaras
  • 71,951
  • 46
  • 188
  • 305
nafsaka
  • 940
  • 2
  • 12
  • 17
0

close the app

Intent intent = new Intent(getApplicationContext(), Splash_Screen.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.putExtra("EXIT", true);
                startActivity(intent);

put this in the oncreate and onResume of the very first activity that is opened. ex. is on splash screen activity

if (getIntent().getBooleanExtra("EXIT", false)) {
            this.finish();
            System.exit(0);
        }
0
in LoginActivity

@Override
    public void onBackPressed() {
        Intent startMain = new Intent(Intent.ACTION_MAIN);
        startMain.addCategory(Intent.CATEGORY_HOME);
        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(startMain);
        finish();
        super.onBackPressed();
    }
0

moveTaskToBack(true);

//add this to the click listner

Kaushik Borah
  • 141
  • 1
  • 4
0
@Override
    public void onBackPressed(){
        MaterialAlertDialogBuilder alert = new MaterialAlertDialogBuilder(BorrowForm.this, MyTheme);
        alert.setTitle("Confirmation");
        alert.setCancelable(false);
        alert.setMessage("App will exit. Data will not be saved. Continue?");
        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast toast = Toast.makeText(BorrowForm.this, "App terminated.", Toast.LENGTH_SHORT);
                toast.getView().setBackgroundColor(Color.parseColor("#273036"));
                toast.setGravity(Gravity.CENTER_HORIZONTAL,0,0);
                TextView toastMessage=(TextView) toast.getView().findViewById(android.R.id.message);
                toastMessage.setTextColor(Color.WHITE);
                toast.show();
                finishAffinity();
            }
        });
        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        alert.setCancelable(false);
        alert.show();
    }
ghunter99
  • 1
  • 1
-9

i am starter in java/android, may be this simple solution help for you

FIRST, create static class

public class ActivityManager {

    static Activity  _step1;
    static Activity _step2;
    static Activity _step3;

    public static void setActivity1(Activity activity)
    {
        _step1 = activity;
    }

    public static void setActivity2(Activity activity)
    {
        _step2 = activity;
    }

    public static void setActivity3(Activity activity)
    {
        _step3 = activity;
    }

    public static void finishAll()
    {
        _step1.finish();
        _step2.finish();
        _step3.finish();
    }

}

THEN when you run new activity save link to your manager(in step 1):

ActivityManager.setActivity1(this);
AddValuesToSharedPreferences();
Intent intent = new Intent(Step1.this, Step2.class);
startActivity(intent);

AND THEN in your last step finish all:

 public void OkExit(View v) throws IOException {
        ActivityManager.finishAll();
    }
  • 2
    Never hold static references to activities. Activities use relatively a lot of memory which should be freed up when activities go to background. static references are held as long as process is alive which application-wise means forever. It's both bad for you as the developer and the user. – Pijusn Nov 22 '14 at 08:09
  • Global variables are serious antipatterns. – ezaquarii Nov 27 '14 at 10:28
  • Terrible. Must never keep a global reference to an activity. – PerracoLabs Mar 16 '18 at 11:51