我想在前台服务运行时在状态栏中更改通知smallIcon
,具体取决于该服务收集的状态,即“静音”或“取消静音”。
要显示smallIcons
资源中的备用res.drawable
,需要做什么?
在服务类的initialize方法中,我目前将静音图标设置如下,但是在启动服务后我不知道如何更改它:
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());
答案 0 :(得分:2)
您只需要保留对NotificationCompat.Builder
的引用。然后使用notify(int id, Notification notification)
的{{1}}方法。
示例:
NotificationManagerCompat
答案 1 :(得分:1)
解决方法是仅创建带有新图标的新通知,以替换旧的通知。
编辑:
这是一个示例代码,用于使用基于名为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)
}
});