如何在服务 运行 期间更改状态栏图标

How to change the status bar icon while service is running

我想在前台服务 运行 时更改状态栏中的通知 smallIcon,具体取决于服务收集的状态,即 "mute" 或 "unmute".

显示 res.drawable 资源中的备用 smallIcons 需要什么?

在服务class的初始化方法中,我目前设置的静音图标如下,不知道服务启动后如何更改:

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

解决方法是只创建一个带有新图标的新通知,这样它就会替换旧的。

编辑: 这是一个示例代码,用于在每次单击按钮时使用基于名为 indicator.

的布尔变量的示例逻辑创建新通知
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //Create the notification builder object
        NotificationCompat.Builder builder = new NotificationCompat.Builder(v.getContext(), NOTE_CHANNEL_ID)
                .setSmallIcon(indicator ? R.drawable.icon1 : R.drawable.icon2)   //TODO: change this line with your logic
                .setContentTitle("Your notification title here")
                .setContentText("Your notificiation text here")
                .setPriority(NotificationCompat.PRIORITY_HIGH)
//                        .setContentIntent(pendingIntent)    //pendingIntent to fire when the user taps on it
                .setAutoCancel(true);   //autoremove the notificatin when the user taps on it

        //show the notification constructed above
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(v.getContext());
        notificationManager.notify(NOTIFICATION_ID, builder.build());

        indicator = !indicator; //switch icon indicator (just for demonstration)
    }
});

您只需要持有对 NotificationCompat.Builder 的引用。然后使用NotificationManagerCompat.

notify(int id, Notification notification)方法

示例:

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