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

时间:2011-06-20 04:08:39

标签: android notifications android-3.0-honeycomb

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

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

是否有人在不调用startForeground()的情况下更新通知?

此行为仅发生在Honeycomb中。姜饼装置(我假设Froyo等)表现得很好。

4 个答案:

答案 0 :(得分:59)

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

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

  • 在构建器
  • 上使用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());
  }
}

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

答案 1 :(得分:23)

答案 2 :(得分: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 );

答案 3 :(得分:-1)

试试这个

    int id = (int) Calendar.getInstance().getTimeInMillis();

在notify()方法中使用此id。您的Android系统本身的时间会创建一个唯一的ID