How do I update the notification text for a foreground service in Android?

后端 未结 5 1964
感情败类
感情败类 2020-12-02 06:25

I have a foreground service setup in Android. I would like to update the notification text. I am creating the service as shown below.

How can I update the notifica

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 07:24

    It seems none of the existing answers show how to handle the full case - to startForeground if it's the first call but update the notification for subsequent calls.

    You can use the following pattern to detect the right case:

    private void notify(@NonNull String action) {
        boolean isForegroundNotificationVisible = false;
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        StatusBarNotification[] notifications = notificationManager.getActiveNotifications();
        for (StatusBarNotification notification : notifications) {
            if (notification.getId() == FOREGROUND_NOTE_ID) {
                isForegroundNotificationVisible = true;
                break;
            }
        }
        Log.v(getClass().getSimpleName(), "Is foreground visible: " + isForegroundNotificationVisible);
        if (isForegroundNotificationVisible){
            notificationManager.notify(FOREGROUND_NOTE_ID, buildForegroundNotification(action));
        } else {
            startForeground(FOREGROUND_NOTE_ID, buildForegroundNotification(action));
        }
    }
    

    Additionally you need to build the notification and channel as in other answers:

    private Notification buildForegroundNotification(@NonNull String action) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createNotificationChannel();
        }
        //Do any customization you want here
        String title;
        if (ACTION_STOP.equals(action)) {
            title = getString(R.string.fg_notitifcation_title_stopping);
        } else {
            title = getString(R.string.fg_notitifcation_title_starting);
        }
        //then build the notification
        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setOngoing(true)
                .build();
    }
    
    @RequiresApi(Build.VERSION_CODES.O)
    private void createNotificationChannel(){
        NotificationChannel chan = new NotificationChannel(CHANNEL_ID, getString(R.string.fg_notification_channel), NotificationManager.IMPORTANCE_DEFAULT);
        chan.setLightColor(Color.RED);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);
    }
    

提交回复
热议问题