Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreground Notification in Android starts new Activity (via pendingIntent) instead of existing one

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?

like image 682
Toni4780 Avatar asked Mar 09 '12 10:03

Toni4780


2 Answers

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().

like image 110
triggs Avatar answered Nov 10 '22 16:11

triggs


//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"
like image 35
Kyaw Kyaw Avatar answered Nov 10 '22 16:11

Kyaw Kyaw