How to deal with android multiple instances?

843 views Asked by At

The launchMode is "singleTop":

<activity android:name=".MainActivity" 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>
    <activity android:name=".GridActivity"></activity>

The MainActivity is the splash screen, when it finish (authenticate with the server) it'll call the GridActivity.

The problem is very specific:

When you install the app from the Google Play the icon will appear in two places: Application Drawer & "Desktop" (launcher screen - default launcher).

Steps to reproduce the problem:

  1. Open the app from the Application Drawer and wait for the GridActivity to be displayed
  2. Press the "home" button to send the application to the background
  3. Open the app from the "Desktop" (device's default launcher)
  4. The application will start in a new instance

I would expect the application will go directly to the GridActivity because of the "singleTop" launchMethod.

BTW, If on step 3 I open the application again from the Application Drawer it works fine, goes directly to the GridActivity.

What am I missing?

1

There are 1 answers

2
Jim On BEST ANSWER

Because you;re using your launch activity as a "splash screen" it is probably getting destroyed, which leads to this behavior. Once it is destroyed, then another process calling it will launch it in a new process. Read this for more:

Android "single top" launch mode and onNewIntent method

The "singleTop" launch mode is probably not necessary. Although to get around this, I use a "first time through" flag that launches the splash screen from the main activity. It seems to work pretty well.

EDIT:

You should be careful to read up on "launchMode" - singleTop and "standard" modes have this behavior, from the docs:

An activity with the "standard" or "singleTop" launch mode can be instantiated multiple times.

http://developer.android.com/guide/topics/manifest/activity-element.html#lmode

You are probably experiencing this aspect of singleTop:

for example, if an existing instance of the "singleTop" activity is in the target task, but not at the top of the stack, or if it's at the top of a stack, but not in the target task — a new instance would be created and pushed on the stack.

The two launch locations are resulting in two different target tasks. This could be because of how the two screens create intents or because the "splashscreen" is destroyed and therefore not present (it is not "only" destroyed by hitting back - Android has several algorithms for destroying activities to conserve processing and memory. You should generally assume that if an activity is not visible, it can be destroyed and re-created at any time).