88

I'm in the process of trying to make a release build of my first android app to send to a few testers. However, I ran into a problem with it. When you exit the app and then re-enter it by launching it via its icon, it restarts the whole app instead of returning to it's previous location. This occurs even if you re-enter right after exiting. However, it does not happen if I hold the Home button and launch it through the recent apps list.

I've searched online for others having this problem and there are a few, but no one has ever had a solid answer as to why it's happening to them. It's been suggested in old questions to set the launchmode to singletask or singleinstance in the manifest file, but that hasn't helped me, and besides - from what I understand, the default behavior for android is to return to the previous state of the task in this situation, so I don't know why I would need special manifest options to make it do that.

The most bizarre thing about this problem is that if I use eclipse and the debugger to put the app on my phone, this problem does not occur. I don't even need to be connected to the debugger, it seems like as long as I have a debug version of the app, the problem doesn't occur. But if I use a release version (I create it using the Android Tools - Export Signed Application Package menu option in Eclipse), the problem happens. If anyone has any insight as to what is causing this, I'd love to hear your thoughts.

tshepang
  • 12,111
  • 21
  • 91
  • 136
LayfieldK
  • 1,086
  • 1
  • 8
  • 9
  • 3
    So apparently if I restart the device that I install the app on, this problem ceases to exist. Now, that's cool and everything, but in my app's case, it will still be extremely annoying for users if it behaves that way prior to a phone restart when they download it. – LayfieldK Apr 21 '13 at 00:06
  • Can you provide a stacktrace or log? – TryTryAgain Apr 21 '13 at 00:16
  • 2
    No, it only happens when I use a release version of the app, so I don't have a stacktrace or log. – LayfieldK Apr 21 '13 at 10:34
  • that wouldn't matter...use an app like aLogcat or something, or ADB into the phone running the release version and look in/extract the logs. – TryTryAgain Apr 22 '13 at 18:09
  • @user2303347 I was having the same issue and spent hours trying to fix it. However the restart on the device fixes the problem. Very weird behaviour – Santiago Apr 24 '13 at 12:43
  • 3
    I've had the same issue, did you ever find out the fix? or cause? or even to be able to recreate the behaviour after restarting the device? - btw I've also found force-stopping the app clears the behaviour – kassim Nov 06 '13 at 10:36
  • 2
    A valid answer for this issue can be found here: http://stackoverflow.com/questions/19545889/app-restarts-rather-than-resumes – Mythul Oct 14 '14 at 17:07
  • @user2303347 have u found solution i m getting same issue ? – Erum May 11 '15 at 04:36
  • me too, same issue.. any help? – exequielc Jun 15 '16 at 23:17
  • @LayfieldK I'm with Kassim in that I can also solve the behavior by force restarting just the app in question. Worth noting that I do NOT observe this behavior for first time installs of an app through debugging via android studio. – ThePartyTurtle Jul 16 '18 at 22:46
  • Another strange cause, restart occurs only when app was launched by clicking on "OPEN" after Copy-to-Device-&-Install. Test on OS8.1, no launchMode in activity. [![enter image description here](https://i.stack.imgur.com/531N3.png)](https://i.stack.imgur.com/531N3.png) – superuser Sep 11 '18 at 07:58

15 Answers15

63

I had the same problem with an application and I resolved this behavior adding flag "android:launchMode="singleTop"" instead of "android:launchMode="singleTask"" in the <activity> declaration of your AndroidManifest.xml file. Hope this will help somebody.

VonD
  • 5,075
  • 2
  • 20
  • 30
sky
  • 662
  • 6
  • 4
  • 3
    This approach is dangerous if we want to open same activity twice with different data. – hkaraoglu Nov 08 '16 at 08:10
  • 7
    If you want to open same activity with different data, you can handle this in onNewIntent(). – Tasneem Mar 02 '17 at 06:03
  • I also found if that I just remove the `android:launchMode` attribute entirely it worked. Not sure if it defaults to "standard" but any ideas would be helpful. I found this great explanation but it's late so it looks like a foreign language to me right now: https://inthecheesefactory.com/blog/understand-android-activity-launchmode/en – Joshua Pinter Aug 26 '17 at 04:54
  • Hi, should I add the android:launchMode="singleTop" to all my activities?. – jmarkstar Jan 05 '19 at 01:17
  • This didn't work in my case. In my app I have a functionality to create and share the link of something. If the app is in background and if the user clicks on the shared link, it opens up a complete new instance of the app if my launchMode is set to 'singleTop' or 'singleInstance'. – tech_human Jun 28 '19 at 19:34
  • when I added this in my project the navigator stopped working.I cannot move into the app – Samiksha Jagtap Oct 16 '19 at 12:14
34

So far I've found out that it's an issue based on how you install it in your real device, specifically:

  1. If you simply copy and paste the APK to your device's local storage and install it from the device, regardless of whether it's signed or unsigned or taken from bin folder, it shows this behavior, app restarts from menu icon.

If you install it using one of the following options, This issue does not appear:

  1. Go to sdk/tools/ using a terminal or command prompt then type

    adb install <FILE PATH OF .APK FILE>
    

    In Linux, type:

    ./adb install <FILE PATH OF .APK FILE>
    
  2. Simply run your project from Eclipse.

I would be pleased to know if there's any possible way to distribute correct APKs for beta testing. I already tried exporting a signed APK because when you copy and paste an APK and install it manually it shows the rogue behavior.

Update:

I found out a solution. Follow these two Steps:

  1. Set android:launchMode="singleTask" = true for all activities of your app in the AndroidMainifest.xml inside the activity tag.
  2. Put this code in your Launcher Activity's onCreate().

    if (!isTaskRoot())
    {
        final Intent intent = getIntent();
        final String intentAction = intent.getAction(); 
        if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && intentAction != null && intentAction.equals(Intent.ACTION_MAIN)) {
            finish();
            return;       
        }
    }
    

This behavior is a bug in Android. Not a special case.

Daniel
  • 2,355
  • 9
  • 23
  • 30
Jayant Arora
  • 1,241
  • 2
  • 15
  • 24
  • 2
    I would not recommend this. launchMode should not just be set. It has to have a purpose as it may cause strange behaviour (talking out of experiences ;) ) – Boy Apr 23 '15 at 08:12
  • If your App supports features like Pin lock, it should be treated carefully when you want to set android:launchMode="singleTask". – Logan Guo Aug 13 '15 at 03:51
11
 // To prevent launching another instance of app on clicking app icon 
        if (!isTaskRoot()
                && getIntent().hasCategory(Intent.CATEGORY_LAUNCHER)
                && getIntent().getAction() != null
                && getIntent().getAction().equals(Intent.ACTION_MAIN)) {

            finish();
            return;
        }

write the above code in your launcher activity before calling setContentView. This will solve the problem

Fathima km
  • 2,539
  • 3
  • 18
  • 26
  • This worked. I was facing crash when app is launched from play store "Open" button and then app is moved to background and then on click of app icon, new instance of app was launching. This fix solved my issue. Thanks – karanatwal.github.io Aug 05 '21 at 07:29
8

You could use launchMode as singleTop to the Launcher Activity in AndroidManifest.xml

       <activity
        android:name="<YOUR_ACTIVITY>"
        android:label="@string/app_name"
        android:launchMode="singleTop">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
vasanth
  • 715
  • 10
  • 23
4

It is the default behavior in Android. For the debug builds it works differently for some reason. It can be solved by adding android:launchMode="singleInstance" to the activity, you want to restart after you launch from the icon.

Reg
  • 10,717
  • 6
  • 37
  • 54
yak32
  • 49
  • 3
4

Add this to your first activity:

if (!isTaskRoot()) {
        finish();
        return;
}     
super.onCreate(savedInstanceState);
Bolling
  • 3,954
  • 1
  • 27
  • 29
  • 2
    this is worked for my case witch is having a splash screen that handle all entry points to an application , so if splash screen already done it job and redirected to the correct place the first time no need to do it again – Ahmed na Jul 27 '19 at 04:46
3

Try using android:alwaysRetainTaskState as shown in the following example:

<activity
    android:name="com.jsnider.timelineplanner.MainActivity"
    android:alwaysRetainTaskState="true"
    android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
Marcel Bro
  • 4,907
  • 4
  • 43
  • 70
jsnid00
  • 528
  • 1
  • 4
  • 8
3

You can try to set android:alwaysRetainTaskState="true" for your launcher activity in AndroidManifest.xml.

    <activity
        android:name=".YourMainActivity"
        android:alwaysRetainTaskState="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

For details you can see https://developer.android.com/guide/topics/manifest/activity-element.html#always

Moven
  • 31
  • 2
3

For me, I found that I had erroneously posted NoHistory = true in my activity attribute

[Activity(NoHistory = true, ScreenOrientation = ScreenOrientation.Landscape)]

This prevented the app resuming into this activity and restarted

Skaterhaz
  • 300
  • 2
  • 12
2

I see this issue on Android TV in 2019. Is there a better fix for it? other than

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

It works but looks like a hack more than the actual solution.

Amit
  • 3,422
  • 3
  • 28
  • 39
0

All of the solutions above didn't work consistently on all of my devices. It worked on some Samsung but not all.

The cause of the problem for me was installing the APK manually.

Alberto M
  • 1,608
  • 1
  • 18
  • 42
0

For me the fix was adding LaunchMode = LaunchMode.SingleTop to my Activity attribute over the Main Activity:

/// <summary>
    /// The main activity of the application.
    /// </summary>
    [Activity(Label = "SilhuettePhone",
        Icon = "@drawable/icon",
        Theme = "@style/MainTheme",
        MainLauncher = true,
        ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation,
        ScreenOrientation = ScreenOrientation.Portrait,
        LaunchMode = LaunchMode.SingleTop,
        WindowSoftInputMode = SoftInput.AdjustResize)]
Calin Vlasin
  • 1,331
  • 1
  • 15
  • 21
0

I had a problem with a restarting app, my problem was in themes: I have differents fragments and I would have one background for all. But this cause a restarting app in some devices(.

I've deleted this line in themes and this helped:

item name ="android:windowBackground">@drawable/background /item

user12927542
  • 151
  • 2
  • 2
0

Removing task affinity rather than launch mode has worked somewhat for as it has its own demerits

Prakhar Kulshreshtha
  • 1,005
  • 11
  • 21
-1

When you press the back button in Android, the onDestroy method is invoked (as opposed to pressing the home button, where only the onPause() method is invoked).

If you need your app to continue where it left off, save the state of the app in your onDestroy() method and load that state in the onCreate() method.

Zoltán
  • 21,321
  • 14
  • 93
  • 134