I’m encountering a problem with my Android app where an activity (ActivityB
) is destroyed when the app is minimized and then reopened from the launcher. However, if I open the app from the recent apps list, ActivityB
is restored correctly.
I start ActivityB
from ActivityA
using the following code:
requireContext().startActivity(
Intent(requireContext(), ActivityB::class.java)
)
The activity is defined in the AndroidManifest.xml with the following attributes:
<activity
android:name=".ActivityB"
android:screenOrientation="portrait"
android:launchMode="singleTop"
android:exported="false"/>
What I’ve tried:
- Setting launchMode to “singleTask”
- Add flag
Intent.FLAG_ACTIVITY_CLEAR_TOP
and
Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
when startingActivityB
How can I ensure that ActivityB is properly restored when reopening the app from the launcher, without being destroyed and recreated?
You can use
android:launchMode="singleInstance"
With the singleInstance flag, there will only ever be one instance of the activity, regardless of how many times it is launched from different parts of the app or even from other apps.
Try not to use singleTask launchMode on your entry Activity (ACTION_MAIN & CATEGORY_LAUNCHER) in case of other Activities being destroyed by Android in the same taskAffinity when user tap on the Launcher to bring your app to foreground.
Alternatively, safely, you could create a splash Activity as entry without any UI for good regardless of other diverse launchMode set on later Activities:
<!-- AndroidManifest -->
<activity
android:name=".SplashActivity"
android:launchMode="standard">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:launchMode="singleTask">
</activity>
// SplashActivity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
startActivity(Intent(this, MainActivity::class.java))
finish()
}