安静地更新正在进行的通知

how*_*ttl 40 notifications android android-3.0-honeycomb

我有一个无线连接到其他设备的服务.启用该服务后,我会持续发出通知,说明它已启用.

启用该服务后,用户将连接到另一台设备.此时,我想更新我正在进行的通知,以说明已连接的设备的名称.通过startForeground(ONGOING_NOTIFICATION, notification)使用更新的信息再次呼叫,这很容易做到; 但每次调用时,它会在条形图上闪烁通知.我真正想要的是通知在后台静默更新而不会在通知栏上闪烁,因此用户在打开通知区域之前不会知道区别.

有没有在没有调用的情况下更新通知startForeground()

此行为仅发生在Honeycomb中.姜饼设备(我假设Froyo等)表现出理想的方式.

Chr*_*dus 60

我也经历过这个问题,在先前的评论和一些挖掘的帮助下,我找到了解决方案.

如果您不希望在更新时闪烁通知,或者不断地占用设备的状态栏,您必须:

  • 在构建器上使用setOnlyAlertOnce(true)
  • 使用SAME Builder进行每次更新.

如果你每次都使用一个新的构建器,那么我猜测Android必须重新重建视图,导致它暂时消失.

一些好代码的例子:

class NotificationExample extends Activity {

  private NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
  private mNotificationManager =
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

  //Different Id's will show up as different notifications
  private int mNotificationId = 1;    

  //Some things we only have to set the first time.
  private boolean firstTime = true;

  private updateNotification(String message, int progress) {
    if (firstTime) {
      mBuilder.setSmallIcon(R.drawable.icon)
      .setContentTitle("My Notification")
      .setOnlyAlertOnce(true);
      firstTime = false;
    }
    mBuilder.setContentText(message)
    .setProgress(100, progress, true);

    mNotificationManager.notify(mNotificationId, mBuilder.build());
  }
}
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,您可以使用消息和进度(0-100)调用updateNotification(String,int),它将更新通知而不会让用户烦恼.

  • +1表示相同的构建器很重要(在文档中找不到).只是自己试了一下:当通知抽屉关闭时没有区别.但是,如果在用户打开通知时发生更新,则通知会消失一段时间,这会产生非常不愉快的眨眼.使用相同的构建器神奇地解决了这个问题.(在4.1.2上测试) (3认同)

den*_*nko 23

您应该更新现有通知https://developer.android.com/training/notify-user/build-notification.html#Updating

  • 在回复之前我确实尝试了你的第一个建议.您的第二个建议导致我在Notification类中的FLAG_ONLY_ALERT_ONCE标志,这导致了正确的行为.谢谢! (14认同)
  • 如果调用setTicker(CharSequence),则Android似乎忽略了FLAG_ONLY_ALERT_ONCE标志,因此如果您只想更新通知,请确保未设置自动收报机文本. (3认同)

Bri*_*itc 7

这对我有用,因为正在进行的活动(而不是服务)通知会"无声地"更新.

NotificationManager notifManager; // notifManager IS GLOBAL
note = new NotificationCompat.Builder(this)
    .setContentTitle(YOUR_TITLE)
    .setSmallIcon(R.drawable.yourImageHere);

note.setOnlyAlertOnce(true);
note.setOngoing(true);
note.setWhen( System.currentTimeMillis() );

note.setContentText(YOUR_MESSAGE);

Notification notification = note.build();
notifManager.notify(THE_ID_TO_UPDATE, notification );
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,`setOnlyAlertOnce(true)` 正是我在通知中更改操作按钮所需的,它不会重新创建(隐藏/显示)新通知。已经浏览了几个小时的 API 并没有意识到我需要这种方法。 (2认同)