Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminate all other previous activities when splash activity starts

Tags:

android

In my app I always want user to start from Splash screen. For example, my app may be open in background and some notification pops up which starts splash activity. This should terminate all previous activities which were running.

I have accomplished this by storing list of all running activities references. And when splash activity starts it just calls

for(runningActivity : runningActivitiesList) {
    runningActivity.finish();
}

This solution works well. However, Android Studio gives me warning of memory leaks when storing references to activities.

Can someone please suggest me a better approach which avoids memory leaks?

like image 625
DR93 Avatar asked Sep 09 '17 11:09

DR93


People also ask

How do I delete my Backstack activity?

Use finishAffinity() to clear all backstack with existing one. Suppose, Activities A, B and C are in stack, and finishAffinity(); is called in Activity C, - Activity B will be finished / removing from stack. - Activity A will be finished / removing from stack. - Activity C will finished / removing from stack.


2 Answers

Maybe enough is to start Activity with clear stack:

Intent intent = new Intent(context, clazz);
intent.setFlags(IntentCompat.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
like image 143
mac229 Avatar answered Oct 17 '22 11:10

mac229


Tried all other options, but only thing worked for me is:

final Intent intent = new Intent(applicationContext, SplashActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK
            | Intent.FLAG_ACTIVITY_NEW_TASK);
    return IntentCompat.makeRestartActivityTask(intent.getComponent());

Please NOTE: This solution is also not full proof. Since, when I open my app through Google Play Store it launches splash activity even when another instance of app is running in background. Thus I end up having 2 instances of the same activity.

like image 44
DR93 Avatar answered Oct 17 '22 09:10

DR93