Update Notification's action Icon dynamically

徘徊边缘 提交于 2020-03-03 03:43:08

问题


I set a notification for a player, I want to update icon after play or pause action from notification. This is my code for Notification.

    private void showNotification(String title, Bitmap bitmap) {

    //region Create Notification
    MediaSessionCompat mediaSession = new MediaSessionCompat(getApplicationContext(), "session tag");
    MediaSessionCompat.Token token = mediaSession.getSessionToken();
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this,"PRIMARY_CHANNEL")
             .setSmallIcon(R.mipmap.ic_launcher_1)
             .setLargeIcon(bitmap)
             .setContentTitle("Simplay")
             .setContentText(title)
             .setOngoing(true)
             .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setContentIntent(notifyPendingIntent)
             .addAction(R.drawable.exo_controls_rewind,"",rewindPendingIntent)
             **.addAction( R.drawable.exo_controls_pause,"",playPendingIntent)**
             .addAction(R.drawable.exo_controls_fastforward,"",forwardPendingIntent)
             .setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle()
             .setMediaSession(token))
             .setPriority(NotificationCompat.PRIORITY_HIGH);

    notificationManager = NotificationManagerCompat.from(this);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = "Notification";
        String description = "";
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel channel = new NotificationChannel("PRIMARY_CHANNEL", name, importance);
        channel.setDescription(description);
        channel.enableLights(true);
        channel.setShowBadge(false);
        channel.setLockscreenVisibility(123);
        NotificationManager notificationManager1 = getSystemService(NotificationManager.class);
        notificationManager1.createNotificationChannel(channel);
    }
    notificationManager.notify(123, mBuilder.build());
    //endregion
}

回答1:


You should use

.addAction(getResources.getDrawable(R.drawable.exo_controls_pause),"",playPendingIntent)



回答2:


Solution To change the icon of action at realtime, you need:

  1. Get and replace action.
  2. Push new notification.

For example:

notificationBuilder.actions[1] = new Notification.Action(R.drawable.pause, "play", pendingIntent);

NotificationManager service = ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE));
service.notify(101, notificationBuilder);

or

notificationBuilder.actions[1] = new Notification.Action(R.drawable.pause, "play", pendingIntent);
startForeground(101, notificationBuilder);


来源:https://stackoverflow.com/questions/58802493/update-notifications-action-icon-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!