如何在Android中更新前台服务的通知文本?

我有Android的前台服务设置。 我想更新通知文本。 我正在创build如下所示的服务。

如何更新在此前台服务中设置的通知文本? 更新通知的最佳做法是什么? 任何示例代码将不胜感激。

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); } 

我在我的主要活动中创build了服务,如下所示:

  // Start Notification Service Intent serviceIntent = new Intent(this, NotificationService.class); startService(serviceIntent); 

我会认为再次调用startForeground()具有相同的唯一ID和Notification与新的信息将工作,虽然我还没有尝试过这种情况。

当你想更新由startForeground()设置的通知时,只需build立一个新的通知,然后使用NotificationManager来通知它。

关键是要使用相同的通知ID。

我没有testing重复调用startForeground()更新通知的情况,但我认为使用NotificationManager.notify会更好。

更新通知不会从前台状态中删除服务(这只能通过调用stopForground来完成);

例:

 private static final int NOTIF_ID=1; @Override public void onCreate (){ this.startForeground(); } private void startForeground() { startForeground(NOTIF_ID, getMyActivityNotification("")); } private Notification getMyActivityNotification(String text){ // The PendingIntent to launch our activity if the user selects // this notification CharSequence title = getText(R.string.title_activity); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MyActivity.class), 0); return new Notification.Builder(this) .setContentTitle(title) .setContentText(text) .setSmallIcon(R.drawable.ic_launcher_b3) .setContentIntent(contentIntent).getNotification(); } /** * This is the method that can be called to update the Notification */ private void updateNotification() { String text = "Some text that will update the notification"; Notification notification = getMyActivityNotification(text); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(NOTIF_ID, notification); } 

这里是你的服务中的代码。 创build一个新的通知,但要求通知pipe理器通知您在startForeground中使用相同的通知ID。

 Notification notify = createNotification(); final NotificationManager notificationManager = (NotificationManager) getApplicationContext() .getSystemService(getApplicationContext().NOTIFICATION_SERVICE); notificationManager.notify(ONGOING_NOTIFICATION, notify); 

对于完整的示例代码,你可以在这里检查:

https://github.com/plateaukao/AutoScreenOnOff/blob/master/src/com/danielkao/autoscreenonoff/SensorMonitorService.java