Search code examples
androidandroid-notificationsandroid-statusbar

How to change the status bar icon while service is running


I want to change the notification smallIcon in the status bar while a foreground service is running, depending on the status the service gathers, namely "mute" or "unmute".

What is needed to display alternate smallIcons from the res.drawable resouce?

In the initialize method of the service class, I currently set the mute icon as follows, but I don't know how to change it after the service was started:

NotificationCompat.Builder builder = new NotificationCompat.Builder(
        this, NOTE_CHANNEL_ID)
        .setSmallIcon(R.drawable.mute_icon)
        .setContentTitle("Calm: Running")
        .setContentText(this.getString(R.string.calm_close_txt))
        .setOngoing(true)
        .setContentIntent(stopIntent);

startForeground(NOTIFICATION_ID, builder.build());

Solution

  • You only need to hold a reference to the NotificationCompat.Builder. Then use the notify(int id, Notification notification) method of NotificationManagerCompat.

    Example:

    NotificationCompat.Builder notificationBuilder;
    
    private void startNotif(){
        notificationBuilder = new NotificationCompat.Builder(
            this, NOTE_CHANNEL_ID)
            .setSmallIcon(R.drawable.mute_icon)
            .setContentTitle("Calm: Running")
            .setContentText(this.getString(R.string.calm_close_txt))
            .setOngoing(true)
            .setContentIntent(stopIntent);
        
        startForeground(NOTIFICATION_ID, notificationBuilder.build());
    }
    
    private void changeIcon(int resID, Context context){
        notificationBuilder.setSmallIcon(resID);
        NotificationManagerCompat notificationManagerCompat =
                    NotificationManagerCompat.from(context);
        notificationManagerCompat.notify(NOTIFICATION_ID, notificationBuilder.build());
    }