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?
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()
.
//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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With