I have a foreground service setup in Android. I would like to update the notification text. I am creating the service as shown below.
How can I update the notification text that is setup within this foreground service? What is the best practise for updating the notification? Any sample code would be appreciated.
public class NotificationService extends Service {
private static final int ONGOING_NOTIFICATION = 1;
private Notification notification;
@Override
public void onCreate() {
super.onCreate();
this.notification = new Notification(R.drawable.statusbar, getText(R.string.app_name), System.currentTimeMillis());
Intent notificationIntent = new Intent(this, AbList.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
this.notification.setLatestEventInfo(this, getText(R.string.app_name), "Update This Text", pendingIntent);
startForeground(ONGOING_NOTIFICATION, this.notification);
}
I am creating the service in my main activity as shown below:
// Start Notification Service
Intent serviceIntent = new Intent(this, NotificationService.class);
startService(serviceIntent);
I would think that calling
startForeground()
again with the same unique ID and aNotification
with the new information would work, though I have not tried this scenario.Update: Based on the comments, you should use NotifcationManager to update the notification and your service continues to stay in the foreground mode. Take a look at the answer below.
Improving on Luca Manzo answer in android 8.0+ when updating the notification it will make sound and show as Heads-up.
to prevent that you need to add
setOnlyAlertOnce(true)
so the code is:
When you want to update a Notification set by startForeground(), simply build a new notication and then use NotificationManager to notify it.
The key point is to use the same notification id.
I didn't test the scenario of repeatedly calling startForeground() to update the Notification, but I think that using NotificationManager.notify would be better.
Updating the Notification will NOT remove the Service from the foreground status (this can be done only by calling stopForground );
Example:
The documentation states
here's the code to do so in your service. Create a new notification, but ask notification manager to notify the same notification id you used in startForeground.
for full sample codes, you can check here:
https://github.com/plateaukao/AutoScreenOnOff/blob/master/src/com/danielkao/autoscreenonoff/SensorMonitorService.java