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



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

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

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

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

您只需要保留对NotificationCompat.Builder的引用。然后使用notify(int id, Notification notification)方法NotificationManagerCompat

例:

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

解决方法是创建一个带有新图标的新通知,以便替换旧通知。

编辑:这是一个示例代码,用于在每次单击按钮时创建新通知,其中包含基于名为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)
}
});

最新更新