Android launch notification starts a new activity (via pendingIntent) instead of the existing one

I have an application for streaming music and I want to display a foreground notification when music is playing. I am streaming in a separate service, and the code that I use to notify the foreground is as follows:

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 displayed on the taskbar, and if I click on the notification, the application opens, but this is a complete new activity (I think due to the creation of a new intention). Therefore, if I have, for example, a dialog box open in the application is not open, if I reject the application (by clicking on it) and then click / click on the application icon in the notification panel. How can I handle this to show "old / real" activity?

+4
source share
3 answers

For this you need to use flags. you can read the flags here: http://developer.android.com/reference/android/content/Intent.html

 notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); 

From the above link:

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

The only top-level flag will start a new activity, if one of them is not already running, if there is already an instance running, then the intention will be sent to onNewIntent() .

+16
source

// 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" 
+3
source

Just use PendingIntent when you create your notification:

 PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), 0, new Intent(getActivity(), WantedActivity.class), 0); 

and do not forget to install it in Notification Builder:

 .setContentIntent(pendingIntent) 
0
source

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


All Articles