Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finishing all activities started before the activity

I want to finish all the activities which are running in the application means want to remove all the parent activities from stack.

I want to implement logout functionality locally in my application so what I was thinking, I will finish all the activities started before and will start login activity again..

like image 613
Pooja M. Bohora Avatar asked Jun 02 '11 06:06

Pooja M. Bohora


2 Answers

Try this one if you're targetting APi Level <11

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
ComponentName cn = intent.getComponent();
Intent mainIntent = IntentCompat.makeRestartActivityTask(cn);
startActivity(mainIntent);
like image 27
Mongi Zaidi Avatar answered Oct 02 '22 01:10

Mongi Zaidi


I should let you know this is not a recommended behavior in android since you should let itself to manage life circles of activities.

However if you really need to do this, you can use FLAG_ACTIVITY_CLEAR_TOP

I give you some sample code here, where MainActivity is the first activity in the application:

public static void home(Context ctx) {
    if (!(ctx instanceof MainMenuActivity)) {
        Intent intent = new Intent(ctx, MainMenuActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        ctx.startActivity(intent);
    }
}

If you want to quit whole application, you can use the following code and check in the MainActivity to quit the application completely:

    public static void clearAndExit(Context ctx) {
    if (!(ctx instanceof MainMenuActivity)) {
        Intent intent = new Intent(ctx, MainMenuActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        Bundle bundle = new Bundle();
        bundle.putBoolean("exit", true);
        intent.putExtras(bundle);
        ctx.startActivity(intent);
    } else {
        ((Activity) ctx).finish();
    }
}

Hope this helps.

like image 62
ThinkChris Avatar answered Oct 02 '22 02:10

ThinkChris