Reputation: 123
I recently migrated to use Android 12's new SplashScreen API and removed the custom splashactivity. The MainActivity
always had launchMode = singleTask
to avoid recreating it multiple times when deeplinking etc. This is also the recommended launchMode
as per Android documentation.
I referred to this and this which conflicts with the actual documentation.
Here's my original manifest:
<activity
android:name=".MainActivity"
android:launchMode="singleTask"
android:screenOrientation="portrait"
android:theme="@style/AppTheme"
android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
With this manifest, if I open any other activity, press Home and open the app again through app launcher, the navigation will reset back to MainActivity (expected, because of the launchMode). My question is why is this a recommended way but at the same time no provision to maintain the back stack?
If I remove the launchMode
(defaults to standard
), I do see activity's onCreate
getting called every time I launch it from Launcher, which shows the Splash again -- this is not desirable. Am I missing anything?
Upvotes: 0
Views: 196
Reputation: 377
Using singleTask with MainActivity in combination with Android 12’s new SplashScreen API can indeed create the behavior you're describing. This launch mode prevents multiple instances of MainActivity from being created, which is helpful for deep linking or other single-entry cases. However, as you've noticed, it can cause navigation to reset when the app is reopened through the launcher, clearing the back stack.
Here’s a breakdown of a couple of approaches that might help achieve the desired behavior:
Option 1: Use FLAG_ACTIVITY_NEW_TASK
One alternative approach is to use launchMode="standard" for MainActivity and add FLAG_ACTIVITY_NEW_TASK in any intent that brings it to the foreground for specific tasks (like from a notification or deep link). This allows you to maintain a back stack, while still preventing multiple instances in cases where the task already exists.
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
Option 2: Use singleTop as a Compromise
singleTop can also be an option, which will allow an existing instance of MainActivity to be reused if it's already at the top of the stack, avoiding the reset behavior. This may result in multiple instances when MainActivity is not at the top, but it can help prevent the splash screen from showing repeatedly.
Each option has trade-offs, so testing which approach best aligns with your navigation requirements is key. Let me know if you'd like to explore one of these in more detail!
Upvotes: 0