Search code examples
androidandroid-activitysingle-instancelaunchmodeandroid-recents

Keep task stack when opening singleInstance activity from recent apps screen


My application contains multiple activities, the main activity (A) is in launchMode singleTop, every over activities are in singleInstance mode.

I've choose singleInstance for preventing illimited navigation if i navigate like this : A -> B -> C -> B -> C -> B -> C The back action will do: C -> B -> A

It works as expected.

Problem : If i navigate A -> B then i open app recents screen, click on my application, activity b is displayed (ok) but if I go back the application exits and returns to android home (the activity is not destroyed, I can always open B since recent apps screen)

Why does task history not retain if I open the application from the recent applications menu?

<activity
        android:name="A"
        android:label="@string/app_name"
        android:launchMode="singleTop"
        android:configChanges="orientation|screenSize"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <meta-data
            android:name="android.app.default_searchable"
            android:value=".SearchResultsActivity" />
    </activity>
    <activity
        android:configChanges="orientation|screenSize"
        android:name="B"
        android:label="B"
        android:launchMode="singleInstance"
        android:theme="@style/AppTheme.NoActionBar">
    </activity>
    <activity
        android:configChanges="orientation|screenSize"
        android:name="C"
        android:label="C"
        android:launchMode="singleInstance"
        android:theme="@style/AppTheme.NoActionBar">
    </activity>

Thanks for your help


Solution

  • If a singleInstance Activity is called, a new task would be created. Through dumpsys, we could find two tasks, but only one task shows in Task Manager. This could be a system bug. And if Activity B set taskAffinity, there could be two tasks in Task Manager.

    Since you start singleInstance B from A, there would be two tasks existed: Task 1 contains Activity A, while task 2 contains Activity B.

    You open the task 2 from the Task Manager which only contains a singleIntance Activity B, so you can not back to Activity A.

    It works well when using back button, because

    Regardless of whether an activity starts in a new task or in the same task as the activity that started it, the Back button always takes the user to the previous activity.

    You can get this from Developer Document: Tasks and Back Stack.

    I suggest you not to use singleInstace mode if it is really really necessary.