Как изменить значок строки состояния во время работы службы - PullRequest
5 голосов
/ 16 июня 2020

Я хочу изменить уведомление smallIcon в строке состояния во время работы службы переднего плана, в зависимости от состояния, которое собирает служба, а именно: «отключить звук» или «включить звук».

Что необходимо отобразить альтернативный smallIcons из ресурса res.drawable?

В методе инициализации класса службы я сейчас установил значок отключения звука следующим образом, но я не знаю, как изменить его после запуска службы:

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

Ответы [ 2 ]

2 голосов
/ 03 июля 2020

Вам нужно только держать ссылку на 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());
}
1 голос
/ 26 июня 2020

Обходной путь - просто создать новое уведомление с новым значком, чтобы оно заменило старый.

РЕДАКТИРОВАТЬ: Вот пример кода для создания нового уведомления каждые при нажатии кнопки с образцом logi c на основе логической переменной с именем 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)
    }
});
...