5

I have a music stream app and I want to display a foreground notification when the music is streaming. I'm doing the streaming in a seperate service and the code I use for the foreground notification is the following:

Notification notification = new Notification(R.drawable.ic_stat_notification, getString(R.string.app_name), System.currentTimeMillis());
Intent notificationIntent = new Intent(this, PlayerActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this,getString(R.string.app_name),
                   getString(R.string.streaming), pendingIntent);
startForeground(4711, notification);

The symbol is shown in the taskbar, and if i click on the notification the app opens up, but it is a total new activity (i guess because of creating a new Intent). So if I have e.g. a dialog open in the app it isn't open if I dismiss the app (clicking home) and then slinding/clickling the app icon in the notification bar. How can I handle this so that the "old/real" activity is shown?

Toni4780
  • 443
  • 1
  • 8
  • 14

2 Answers2

16

You need to use flags for this. you can read up on flags here: http://developer.android.com/reference/android/content/Intent.html

notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

From the link above:

If set, the activity will not be launched if it is already running at the top of the history stack.

The single top flag will start a new activty if one isn't already running, if there is an instance already running then the intent will be sent to onNewIntent().

Sheraz Ahmad Khilji
  • 8,300
  • 9
  • 52
  • 84
triggs
  • 5,890
  • 3
  • 32
  • 31
  • bad you didn't mention `android:launchMode="singleTop"` as user http://stackoverflow.com/a/13876977/4548520 – user25 Feb 04 '17 at 19:01
6

//in your Activity

Notification notification = new Notification(R.drawable.ic_stat_notification, getString(R.string.app_name), System.currentTimeMillis());
Intent notificationIntent = new Intent(this, PlayerActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this,getString(R.string.app_name),
                   getString(R.string.streaming), pendingIntent);
startForeground(4711, notification);

//In your Manifest

android:name="com.package.player.MusicPlayerActivity"

android:launchMode="singleTop"
Kyaw Kyaw
  • 128
  • 2
  • 4