4

My goal is to return back to last activity if user click in notification. I create the notification from in the service onCreate() in this way:

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 this go to the MainActivity and not to the last one opened before to click home button.

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

Thank's.

Giuseppe
  • 1,079
  • 13
  • 31
  • _+1_ here is the best solution http://stackoverflow.com/questions/31448840/android-how-to-open-last-activity-when-tapping-notification – nAkhmedov Jul 22 '15 at 10:59

2 Answers2

6

Just use the same intent filters as android uses when launches the app:

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

As the intent you created to open your activity from notification bar is the same as android used for launching your app, the previously opened activity will be shown instead of creating a new one.

Prabu
  • 1,441
  • 15
  • 20
5

Use the below code..

 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 to SingleTop or SingleInstance in Android Manifest, then instead of creating a new activity it just reopen the one still active.

Vikash Kumar
  • 621
  • 2
  • 6
  • 21
  • You just check these link, you will get the solution. [Custom Notification](http://stackoverflow.com/questions/3079652/custom-notification) [Last Activity](http://stackoverflow.com/questions/9188412/how-to-open-last-activity-from-notification-status-bar) [example](http://stackoverflow.com/questions/4089213/android-notification-bar-open-last-active-activity) – Vikash Kumar May 15 '12 at 09:14
  • 1
    is this line important ? (notification.setLatestEventInfo(getApplicationContext(), contentTitle, contentText, contentIntent);). Because now, it's deprecated. Thanks – Cocorico Jul 18 '14 at 15:26