[java] Finish all previous activities

My application has the following flow screens :

Home->screen 1->screen 2->screen 3->screen 4->screen 5

Now I have a common log out button in each screens

(Home/ screen 1 / screen 2 /screen 3/ screen 4 / screen 5)

I want that when user clicks on the log out button(from any screen), all the screens will be finished and a new screen Log in will open .

I have tried nearly all FLAG_ACTIVITY to achieve this. I also go through some answers in stackoverflow, but not being able to solve the problem. My application is on Android 1.6 so not being able to use FLAG_ACTIVITY_CLEAR_TASK

Is there any way to solve the issue ?

This question is related to java android android-activity screen flow

The answer is


Before launching your new Activity, simply add the following code:

finishAffinity();

Or if you want it to work in previous versions of Android:

ActivityCompat.finishAffinity(this);

Log in->Home->screen 1->screen 2->screen 3->screen 4->screen 5

on screen 4 (or any other) ->

StartActivity(Log in)
with
FLAG_ACTIVITY_CLEAR_TOP


I guess I am late but there is simple and short answer. 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 below 16, use

ActivityCompat.finishAffinity(YourActivity.this);

Hope it helps!

shareedit answered May 27 '18 at 8:03

Akshay Taru


For logout button on last screen of app, use this code on logout button listener to finish all open previous activities, and your problem is solved.

{
Intent intent = new Intent(this, loginScreen.class);
ntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}

A solution I implemented for this (I think I found it on Stack Overflow somewhere, but I don't remember, so thanks to whoever did that in the first place):

From any of your activities do this:

// Clear your session, remove preferences, etc.
Intent intent  = new Intent(getBaseContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

Then in your LoginActivity, overwrite onKeyDown:

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(true);
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

On a side note, good to know
This answer works (https://stackoverflow.com/a/13468685/7034327)

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
this.finish();

whereas this doesn't work

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

.setFlags() replaces any previous flags and doesn't append any new flags while .addFlags() does.

So this will also work

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

Intent intent = new Intent(this, classObject);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

This Will work for all Android versions. Where IntentCompat the class added in Android Support library.


    Intent i1=new Intent(getApplicationContext(),StartUp_Page.class);
i1.setAction(Intent.ACTION_MAIN);
i1.addCategory(Intent.CATEGORY_HOME);
i1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i1);
finish();

When the user wishes to exit all open activities, they should press a button which loads the first Activity that runs when your application starts, clear all the other activities, then have the last remaining activity finish. Have the following code run when the user presses the exit button. In my case, LoginActivity is the first activity in my program to run.

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

The above code clears all the activities except for LoginActivity. Then put the following code inside the LoginActivity's onCreate(...), to listen for when LoginActivity is recreated and the 'EXIT' signal was passed:

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

Why is making an exit button in Android so hard?

Android tries hard to discourage you from having an "exit" button in your application, because they want the user to never care about whether or not the programs they use are running in the background or not.

The Android OS developers want your program to be able to survive an unexpected shutdown and power off of the phone, and when the user restarts the program, they pick up right where they left off. So the user can receive a phone call while they use your application, and open maps which requires your application to be freed for more resources.

When the user resumes your application, they pick up right where they left off with no interruption. This exit button is usurping power from the activity manager, potentially causing problems with the automatically managed android program life cycle.


for API >= 15 to API 23 simple solution.

 Intent nextScreen = new Intent(currentActivity.this, MainActivity.class);
 nextScreen.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
 startActivity(nextScreen);
 ActivityCompat.finishAffinity(currentActivity.this);

If you log in the user in screen 1 and from there you go to the other screens, use

Intent intent = new Intent(this, Screen1.class);
intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

You may try Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK. It will totally clears all previous activity(s) and start new activity.


I found this solution to work on every device despite API level (even for < 11)

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

Best way to close all the previous activities and clear the memory

finishAffinity()
System.exit(0);

From developer.android.com:

public void finishAffinity ()

Added in API level 16

Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and in to its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch.

Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.


In my case I use finishAffinity() function in last activity like:

finishAffinity()
startHomeActivity()

Hope it'll be useful.


instead of using finish() just use finishAffinity();


If you are using startActivityForResult() in your previous activities, just override OnActivityResult() and call the finish(); method inside it in all activities.. This will do the job...


I guess I am late but there is simple and short answer. 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 below 16, use

ActivityCompat.finishAffinity(YourActivity.this);

Hope it helps!


If your application has minimum sdk version 16 then you can use finishAffinity()

Finish this activity as well as all activities immediately below it in the current task that have the same affinity.

This is work for me In Top Payment screen remove all back-stack activits,

@Override
public void onBackPressed() {
         finishAffinity();
        startActivity(new Intent(PaymentDoneActivity.this,Home.class));
    } 

http://developer.android.com/reference/android/app/Activity.html#finishAffinity%28%29


I found this way, it'll clear all history and exit

Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
Intent intent = new Intent(getApplicationContext(), SplashScreen.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

finish();
System.exit(0);

Use the following for activity

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);

remove CLEAR_TASK flag for fragment use.

I hope this may use for some people.


When user click on the logout button then write the following code:

Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

And also when after login if you call new activity do not use finish();


i have same problem you can use IntentCompat , like this :

import android.support.v4.content.IntentCompat;
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);

this code work for me .

Android api 17


Simply, when you go from the login screen, not when finishing the login screen.

And then in all forward activities, use this for logout:

final Intent intent = new Intent(getBaseContext(), LoginScreen.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);

It works perfectly.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-activity

Kotlin Android start new Activity The activity must be exported or contain an intent-filter How to define dimens.xml for every different screen size in android? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Not an enclosing class error Android Studio java.lang.IllegalStateException: Fragment not attached to Activity Soft keyboard open and close listener in an activity in Android android.app.Application cannot be cast to android.app.Activity Android Shared preferences for creating one time activity (example) Android ListView with onClick items

Examples related to screen

How to make flutter app responsive according to different screen size? Unable to capture screenshot. Prevented by security policy. Galaxy S6. Android 6.0 Clear screen in shell How to detect iPhone 5 (widescreen devices)? How to develop or migrate apps for iPhone 5 screen resolution? Android splash screen image sizes to fit all devices How to support different screen size in android Finish all previous activities Android screen size HDPI, LDPI, MDPI How to get the screen width and height in iOS?

Examples related to flow

Finish all previous activities