How to correctly handle startForegrounds two notifications

大城市里の小女人 提交于 2019-12-01 03:48:28

First off, judging by your description, you might be able to get away with a regular service, recognizing that the out-of-memory killer won't come calling unless things are getting dire on the device and your service has really been running a very long time.

That said, if you must make the service foreground, the typical strategy here is to show your progress using the Notification you used when you put your service into the foreground state. Using NotificationManager.notify you can post as many updates to that notification as you like, including adjustments to progress bars via Notification.Builder.setProgress, for example.

In this way you only show one notification to the user, and it's the one required by startForeground.

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:

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); } 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!