Android: How to show/skip the Splash Screen as needed when opening an app through a notification?

Viewed 589

(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:

  1. 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 calls finish() to finish itself.
  2. 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:

  1. If MainActivity already exists (either in the background or foreground), open that same instance.
  2. If MainActivity was destroyed (the user previously pressed Back), then open the SplashActivity. The splash activity will redirect you itself to MainActivity.

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.

1 Answers

in the manifest you should add the following to your main activity

android:launchMode="singleTask"

then my notification looks as follows

NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context, MainActivity.NOTIFICATION_CHANNEL_ID)
                        .setSmallIcon(R.drawable.ic_notification)
                        .setContentTitle(title)
                        .setContentText(text)
                        .setStyle(new NotificationCompat.BigTextStyle()
                                .bigText(text));

mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);

Intent goToAppIntent = context.getPackageManager()
                .getLaunchIntentForPackage(context.getPackageName())
                .setPackage(null)
                .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

PendingIntent piGoToApp = PendingIntent.getActivity(context, 0, goToAppIntent, 0);
mBuilder.addAction(0,"go to app",piGoToApp);
mBuilder.setContentIntent(piGoToApp);

let me know if it helps

Related