(Note: My app's targetSdk and compileSdk are set to 29, so I can't take advantage of the new SplashScreen API)
I have a very simple app with two activities:
- SplashActivity - Default activity opened with the launcher icon. Shows a splash screen, loads some stuff, and when complete, calls
startActivity()to start the Main Activity and then callsfinish()to finish itself. - Main Activity - It just posts a notification. When pressing that notification, the app should be brought to the foreground.
What do I mean by "the app should be brought to the foreground"? To be clear:
- If
MainActivityalready exists (either in the background or foreground), open that same instance. - If
MainActivitywas destroyed (the user previously pressed Back), then open theSplashActivity. The splash activity will redirect you itself toMainActivity.
In fact, this is exactly the default behavior of the launcher icon.
However, I can't get my app to behave this way when the notification is pressed. Either it's always opening the SplashScreen, or it's always opening the MainActivity directly and skipping the Splash Screen.
Ideally, I would like to do this:
Intent intent;
if (MainActivity already exists) {
// Bring that instance of MainActivity to the foreground
intent = new Intent(this, MainActivity.class);
} else {
// No UI activity exists for the app. Start from the Splash Screen.
intent = new Intent(this, SplashActivity.class);
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
...
// later
notificationBuilder.setContentIntent(pendingIntent);
But I'm pretty sure I shouldn't be checking for the existence of MainActivity myself. I should be using a combination of Intent Flags and activity launch modes.