App completely restarting when launched by icon press in launcher

 // 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


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.


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.