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

标签 android android-notifications android-statusbar

我要更改通知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());

最佳答案

解决方法是创建一个带有新图标的新通知,这样它就会替换旧的。
编辑:
这是一个示例代码,用于在每次单击按钮时创建一个新通知,其中包含基于 bool 变量 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)
    }
});

关于android - 如何在服务运行时更改状态栏图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62412781/

相关文章:

android - 在 AndroidManifest 中有条件地声明服务

android - 如何从存储在外部存储器中的音频文件设置 Android 铃声

android - 如何在android系统状态栏中显示文字

android - 使用 InputMethodManager 的软件键盘导致堆栈溢出错误

iphone - 在 Titanium 中,如何从代码执行按钮单击事件?

android - Android 应用程序数据库中更新文件的通知

android - 当收到多个 Android 通知时,只有最新的一个上的操作按钮有效

android - 如何在应用程序被杀死时在状态栏上保持通知?

Android 全屏应用程序 - 阻止访问状态栏