Updating an ongoing notification quietly

后端 未结 4 1454
感动是毒
感动是毒 2020-11-29 01:55

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 servi

相关标签:
4条回答
  • 2020-11-29 02:15

    Try this

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

    Use this id in the notify() method. Time of your Android System itself creates a unique ID

    0 讨论(0)
  • 2020-11-29 02:26

    You should update existing notification https://developer.android.com/training/notify-user/build-notification.html#Updating

    0 讨论(0)
  • 2020-11-29 02:30

    I too experienced this issue, and with help of previous comments and a bit of digging I have found the solution.

    If you do not want notifications to flash when updated, or to continuously hog the status bar of the device,you must:

    • Use setOnlyAlertOnce(true) on the builder
    • Use the SAME Builder for each update.

    If you use a new builder each time, then I am guessing Android has to rebuild the view all over again causing it to briefly disappear.

    An example of some good code:

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

    With the above code, you can just call updateNotification(String, int) with a message and progress (0-100) and it will update the notification without annoying the user.

    0 讨论(0)
  • 2020-11-29 02:39

    This worked for me, whereby an ongoing activity (not SERVICE) notification is updated 'silently'.

    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 );
    
    0 讨论(0)
提交回复
热议问题