android 以静默方式更新正在进行的通知

ltskdhd1  于 2022-12-02  发布在  Android
关注(0)|答案(4)|浏览(358)

I have a service which connects to other devices wirelessly. When the service is enabled, I have an ongoing notification which states it is enabled.
After the service is enabled, the user then connects to another device. At this point, I would like to update my ongoing notification to state the name of the device which has been connected to. This is easy enough to do by calling startForeground(ONGOING_NOTIFICATION, notification) again with the updated information; however this flashes the notification on the bar each time it is called. What I would really like is the notification to quietly update in the background without flashing on the notification bar so the user doesn't know the difference until he or she opens the notification area to look.
Is there someway to update the notification without calling startForeground() ?
This behavior only occurs in Honeycomb. Gingerbread devices (and I assume Froyo, etc.) behave the desired way.

vhipe2zx

vhipe2zx1#

我也经历过这个问题,在以前的评论和一点挖掘的帮助下,我找到了解决办法。
如果您不希望更新时通知闪烁,或持续占据设备的状态栏,则必须:

  • 在生成器上使用setOnlyAlertOnce(true)
  • 每次更新都使用相同的构建器。

如果你每次都使用一个新的构建器,那么我猜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());
  }
}

使用上面的代码,您可以只调用updateNotification(String,int),其中包含消息和进度(0-100),它将更新通知,而不会打扰用户。

bf1o4zei

bf1o4zei2#

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

42fyovps

42fyovps3#

这对我很有效,一个正在进行的活动(不是服务)通知被“无声地”更新。

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

raogr8fs4#

试试这个

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

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

相关问题