App restarts rather than resumes

AndroidAndroid Lifecycle

Android Problem Overview


Hopefully someone can help me figure out, if not a solution, at least an explanation for a behaviour.

The Problem:

On some devices, pressing the launcher icon results in the current task being resumed, on others it results in the initial launch intent being fired (effectively restarting the app). Why does this happen?

The Detail:

When you press the "Launcher Icon" the app starts normally - That is, I assume, an Intent is launched with the name of your first Activity with the action android.intent.action.MAIN and the category android.intent.category.LAUNCHER. This can't always be the case however:

On the majority of devices, if you press the launcher icon after the app is already running, the currently running Activity in that process is resumed (NOT the initial Activity). It resumes in the same way as if you had selected it from the "Recent Tasks" in the OS menu. This is the behaviour I want on all devices.

However, on selected other devices different behaviour occurs:

  • On the Motorola Xoom, when you press the launcher icon, the App will always start the initial launch Activity regardless of what is currently running. I assume that the launcher icons always start the "LAUNCHER" intent.

  • On the Samsung Tab 2, when you press the launcher icon, if you have just installed the app, it will always launch the initial Activity (Same as the Xoom) - however, after you restart the device after the install, the launcher icon will instead resume the app. I assume that these devices add "installed apps" into a lookup table on device startup which allow the launcher icons to correctly resume running tasks?

I've read many answer that sound similar to my problem but simply adding android:alwaysRetainTaskState="true" or using launchMode="singleTop" to the Activity are not the answer.

Edit:

After the most recent launch of this app, we find that this behaviour has begun to occur on all devices after the first restart. Which seems crazy to me but looking through the restart process, I can't actually find what's going wrong.

Android Solutions


Solution 1 - Android

The behavior you are experiencing is caused by an issue that exists in some Android launchers since API 1. You can find details about the bug as well as possible solutions here: https://code.google.com/p/android/issues/detail?id=2373.

It's a relatively common issue on Samsung devices as well as other manufacturers that use a custom launcher/skin. I haven't seen the issue occur on a stock Android launcher.

Basically, the app is not actually restarting completely, but your launch Activity is being started and added to the top of the Activity stack when the app is being resumed by the launcher. You can confirm this is the case by clicking the back button when you resume the app and are shown the launch Activity. You should then be brought to the Activity that you expected to be shown when you resumed the app.

The workaround I chose to implement to resolve this issue is to check for the Intent.CATEGORY_LAUNCHER category and Intent.ACTION_MAIN action in the intent that starts the initial Activity. If those two flags are present and the Activity is not at the root of the task (meaning the app was already running), then I call finish() on the initial Activity. That exact solution may not work for you, but something similar should.

Here is what I do in onCreate() of the initial/launch Activity:

    if (!isTaskRoot()
            && getIntent().hasCategory(Intent.CATEGORY_LAUNCHER)
            && getIntent().getAction() != null
            && getIntent().getAction().equals(Intent.ACTION_MAIN)) {

        finish();
        return;
    }

Solution 2 - Android

This question is still relevant in 2016. Today a QA tester reported an app of mine restarting rather than resuming from the stock launcher in Android M.

In reality, the system was adding the launched activity to the current task-stack, but it appeared to the user as if a restart had occurred and they'd lost their work. The sequence was:

  1. Download from play store (or sideload apk)
  2. Launch app from play store dialog: activity A appears [task stack: A]
  3. Navigate to activity B [task stack: A -> B]
  4. Press 'Home' button
  5. Launch app from app drawer: activity A appears! [task stack: A -> B -> A] (user could press 'Back' button to get to activity 'B' from here)

Note: this problem does not manifest for debug APK's deployed via ADB, only in APKs downloaded from the Play Store or side-loaded. In the latter cases, the launch intent from step 5 contained the flag Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT, but not in the debug cases. The problem goes away once the the app has been cold-started from the launcher. My suspicion is the Task is seeded with a malformed (more accurately, non-standard) Intent that prevents the correct launch behavior until the task is cleared entirely.

I tried various activity launch modes, but those settings deviate too much from standard behavior the user would expect: resuming the task at activity B. See the following definition of expected behavior in the guide to Tasks and Back Stack, at the bottom of the page under 'Starting a Task':

> An intent filter of this kind causes an icon and label for the activity to be displayed in the application launcher, giving users a way to launch the activity and to return to the task that it creates any time after it has been launched.

I found this answer to be relevant and inserted the following into the 'onCreate' method of my root activity (A) so that it resumes appropriately when the user opens the application.

                    /**
     * Ensure the application resumes whatever task the user was performing the last time
     * they opened the app from the launcher. It would be preferable to configure this
     * behavior in  AndroidMananifest.xml activity settings, but those settings cause drastic
     * undesirable changes to the way the app opens: singleTask closes ALL other activities
     * in the task every time and alwaysRetainTaskState doesn't cover this case, incredibly.
     *
     * The problem happens when the user first installs and opens the app from
     * the play store or sideloaded apk (not via ADB). On this first run, if the user opens
     * activity B from activity A, presses 'home' and then navigates back to the app via the
     * launcher, they'd expect to see activity B. Instead they're shown activity A.
     *
     * The best solution is to close this activity if it isn't the task root.
     *
     */

    if (!isTaskRoot()) {
        finish();
        return;
    }

UPDATE: moved this solution away from parsing intent flags to querying if the activity is at the root of the task directly. Intent flags are difficult to predict and test with all the different ways there are to open a MAIN activity (Launch from home, launch from 'up' button, launch from Play Store, etc.)

Solution 3 - Android

Aha! (tldr; See the statements in bold at the bottom)

I've found the problem... I think.

So, I'll start off with a supposition. When you press the launcher, it either starts the default Activity or, if a Task started by a previous launch is open, it brings it to the front. Put another way - If at any stage in your navigation you create a new Task and finish the old one, the launcher will now no longer resume your app.

If that supposition is true, I'm pretty sure that should be a bug, given that each Task is in the same process and is just as valid a resume candidate as the first one created?

My problem then, was fixed by removing these flags from a couple of Intents:

i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK );

While it's quite obvious the FLAG_ACTIVITY_NEW_TASK creates a new Task, I didn't appreciate that the above supposition was in effect. I did consider this a culprit and removed it to test and I was still having a problem so I dismissed it. However, I still had the below conditions:

i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)

My splash screen was starting the "main" Activity in my app using the above flag. Afterall, If I had "restart" my app and the Activity was still running, I would much rather preserve it's state information.

You'll notice in the documentation it makes no mention of starting a new Task:

> If set, and the activity being launched is already running in the > current task, then instead of launching a new instance of that > activity, all of the other activities on top of it will be closed and > this Intent will be delivered to the (now on top) old activity as a > new Intent. > > For example, consider a task consisting of the activities: A, B, C, D. > If D calls startActivity() with an Intent that resolves to the > component of activity B, then C and D will be finished and B receive > the given Intent, resulting in the stack now being: A, B. > > The currently running instance of activity B in the above example will > either receive the new intent you are starting here in its > onNewIntent() method, or be itself finished and restarted with the new > intent. If it has declared its launch mode to be "multiple" (the > default) and you have not set FLAG_ACTIVITY_SINGLE_TOP in the same > intent, then it will be finished and re-created; for all other launch > modes or if FLAG_ACTIVITY_SINGLE_TOP is set then this Intent will be > delivered to the current instance's onNewIntent(). > > This launch mode can also be used to good effect in conjunction with > FLAG_ACTIVITY_NEW_TASK: if used to start the root activity of a task, > it will bring any currently running instance of that task to the > foreground, and then clear it to its root state. This is especially > useful, for example, when launching an activity from the notification > manager.

So, I had the situation as described below:

  • A launched B with FLAG_ACTIVITY_CLEAR_TOP, A finishes.
  • B wishes to restart a service so sends the user to A which has the service restart logic and UI (No flags).
  • A launches B with FLAG_ACTIVITY_CLEAR_TOP, A finishes.

At this stage the second FLAG_ACTIVITY_CLEAR_TOP flag is restarting B which is in the task stack. I'm assuming this must destroy the Task and start a new one, causing my problem, which is a very difficult situation to spot if you ask me!

So, if all of my supposition are correct:

  • The Launcher only resumes the initially created Task
  • FLAG_ACTIVITY_CLEAR_TOP will, if it restarts the only remaining Activity, also recreate a new Task

Solution 4 - Android

I had the same issue on Samsung devices. After searching a lot, none of these answers worked for me. I found that in the AndroidManifest.xml file, launchMode is set to singleInstance (android:launchMode="singleInstance"). Removing the launchMode attribute fixed my issue.

Solution 5 - Android

On my Cat s60, I had enabled "Don't keep activities" in Developer options, disabling this again allowed me to switch apps without loosing state of the apps...

Solution 6 - Android

This solution worked for me:

    @Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent startMain = new Intent(Intent.ACTION_MAIN);
			startMain.addCategory(Intent.CATEGORY_HOME);
			startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(startMain);
			return false;
		}
		else
			return super.onKeyUp(keyCode, event);
	}

credit: https://stackoverflow.com/questions/28162815/i-need-to-minimize-the-android-application-on-back-button-click

may not work on all devices, but successfully creates home button behavior when back button is pressed, thus stopping the activity rather than finishing it.

Solution 7 - Android

I had the same problem, the cause was:

(Kotlin code, in MainActivity)

override fun onBackPressed() {
    finish()
}

So when navigating to my MainActivity from my LoginActivity I use this:

    val intent = Intent(this, MainActivity::class.java)
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    startActivity(intent)

When using these flags I dont have to have a onBackPressed() in my MainActivity, it will exit the app naturally on back click. And when pressing the Home button and going back into the app it dosen't restart.

Solution 8 - Android

Solution for the people who have no idea about programming and experiencing this issue in their android phone. This happens mostly due to upgrade of android version(only my assumption). After upgrade all your apps gets optimized to use less battery. But, this in turn slows down your device.

How to solve

Go to settings>>Apps>>apps settings(look for settings sign anywhere on the screen- it is different on different devices)>>battery optimization(or similar opti[enter image description here][1]on)>> move all apps to 'not optimised' state (have to do 1 by 1 manually -may be allow/disallow in some phones). Your launcher app need to be 'not optimised'(Zen UI launcher in my case - this is the culprit I guess- you could try optimising/Not optimizing and restarting different app if you have time). Now restart your phone. (no need to reset data/safe mode or any trouble)

Try multitasking now. :) Pressing the launcher icon should now results in the current task being resumed. :) Your device will become Don't worry about battery, it will drain anyway.

Solution 9 - Android

Priceless to your users. The perfect resume even after sitting weeks in the recently used app list.

It looks like a resume to the user but actually is a full blown start.

Background: The memory used by apps that are in the main activity that haven't started a task is easy to reclaim. The os can simply restart the app with the original bundle passed to onCreate. You can however add to the original bundle in onSaveInstanceState so when your app is restarted by the OS you can restore the instance state and no one is the wiser on whether the app restarted or resumed. Take for example the classic map program. The user moves to a position on the map and then presses the home key. Two weeks later this mapping app is still in the list of recent apps along with facebook, pandora, and candy crush. The OS doesn't just save the name of the app for the recently used apps it also saves the original bundle used to start the app. However the programmer has coded the onSaveInstanceState method so the orignal bundle now contains all the materials and information necessary to construct the app so it looks like it was resumed.

Example: Save the current camera position in onSaveInstanceState just incase the app is unloaded and has to be restarted weeks later from the list of recent apps.

@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);
		// save the current camera position;
		if (mMap != null) {
			savedInstanceState.putParcelable(CAMERA_POSITION,
					mMap.getCameraPosition());
		}
	}



@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

        // get the exact camera position if the app was unloaded.
        if (savedInstanceState != null) {
			// get the current camera position;
			currentCameraPosition = savedInstanceState
					.getParcelable(CAMERA_POSITION);
		}

Note: you can also use the onRestoreInstanceState method but I find it easier to restore the instance in onCreate.

This is more than likely what is happening in your app. On some devices your app is unloaded to free memory. Yes there are some flags that help but the flags will not pick up every nuance of your app and the flags won't keep you alive for weeks like onSaveInstanceState will. You have to code the perfect two weeks later resume. It will not be an easy task for the complex app but we are behind you and are here to help.

Good Luck

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
QuestionGraemeView Question on Stackoverflow
Solution 1 - Androidstarkej2View Answer on Stackoverflow
Solution 2 - AndroidRich EhmerView Answer on Stackoverflow
Solution 3 - AndroidGraemeView Answer on Stackoverflow
Solution 4 - AndroidAliView Answer on Stackoverflow
Solution 5 - AndroidptpView Answer on Stackoverflow
Solution 6 - AndroidRussell ChisholmView Answer on Stackoverflow
Solution 7 - AndroidChristerView Answer on Stackoverflow
Solution 8 - AndroidArun AntonyView Answer on Stackoverflow
Solution 9 - Androiddanny117View Answer on Stackoverflow