Android: restore the latest activity from a notification

My goal is to return to the last action if the user clicks on the notification. I am creating a notification from the onCreate () service as follows:

Intent notificationIntent = new Intent(this, MainActivity.class); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 

but when I click on the notification, go to MainActivity, and not to the last one opened before clicking the home button.

In the manifest, I tried with MainActivity with launchMode = "singleTop", "standard" and "singletask", but without success.

Thank x.

+4
source share
2 answers

Use the code below.

  contentTitle = "MyApp"; contentText = "Reopen App"; notificationIntent = new Intent(this, MainActivity.class); contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(getApplicationContext(), contentTitle, contentText, contentIntent); 

And set the Activity for SingleTop or SingleInstance in the Android manifest, instead of creating a new activity, it just opens the active.

+5
source

Just use the same intent filters as when using Android when starting the application:

  final Intent notificationIntent = new Intent(context, YourActivity.class); notificationIntent.setAction(Intent.ACTION_MAIN); notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER); 

Since the intention that you created to open your activity in the notification panel is the same as the android used to launch your application, the previously created action will be shown instead of creating a new one.

+5
source

Source: https://habr.com/ru/post/1412352/


All Articles