通知中的播放/暂停按钮图像,Android

我已经实现了音乐播放器,可以在播放流音频时触发自定义通知

一切正常,我可以使用通知中的按钮播放/暂停音频。 唯一的问题是图像按钮:单击按钮无法更改图像以指示播放/暂停。

在RemoteReceiver中使用remoteViews.setImageViewResource()不起作用。 控件是使用BroadcastReceiver完成的,这是从玩家活动中触发通知的代码:

public void setNotification(String songName){ String ns = Context.NOTIFICATION_SERVICE; NotificationManager notificationManager = (NotificationManager) getSystemService(ns); @SuppressWarnings("deprecation") Notification notification = new Notification(R.drawable.ic_launcher, null, System.currentTimeMillis()); RemoteViews notificationView = new RemoteViews(getPackageName(), R.layout.notification_view); notificationView.setImageViewResource(R.id.button1, R.drawable.pause); notificationView.setTextViewText(R.id.textView1, songName); //the intent that is started when the notification is clicked (works) Intent notificationIntent = new Intent(this, PlayerActivity.class); PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); notification.contentView = notificationView; notification.contentIntent = pendingNotificationIntent; Intent switchIntent = new Intent("com.example.test.ACTION_PLAY"); PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0, switchIntent, PendingIntent.FLAG_UPDATE_CURRENT); notificationView.setOnClickPendingIntent(R.id.play_pause, pendingSwitchIntent); notificationManager.notify(1, notification); } 

notification.xml内容是

      

这是RemoteRecivier类

 public class RemoteControlReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.notification_view); if(action.equalsIgnoreCase("com.example.test.ACTION_PLAY")){ if(mediaplayer.isPlaying()){ mediaplayer.pause(); remoteViews.setImageViewResource(R.id.button1, R.drawable.play); } else { mediaplayer.start(); remoteViews.setImageViewResource(R.id.button1, R.drawable.pause); } } } } 

最后,清单是

        

您必须在更改后将notification.contentView设置为新的remoteView,以便它可以更新通知视图本身。

这意味着,在BroadcastReceiver中收到操作后,使用所需的按钮显示(暂停或播放)重新构建通知

希望这可以帮助

这应该工作。 只需将您的notificationnotificationManager静态全局variables即可。

 public class RemoteControlReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(action.equalsIgnoreCase("com.example.test.ACTION_PLAY")){ if(mediaplayer.isPlaying()){ mediaplayer.pause(); notificationView.setImageViewResource(R.id.button1, R.drawable.play); notification.contentView = notificationView; notificationManager.notify(1, notification); } else { mediaplayer.start(); notificationView.setImageViewResource(R.id.button1, R.drawable.pause); notification.contentView = notificationView; notificationManager.notify(1, notification); } } } } 

为什么不使用ImageView而不是ImageButton? 使用ImageView,您只需使用removeViews.setImageViewResource(R.id.button1, R.drawable.pause);更改其外观removeViews.setImageViewResource(R.id.button1, R.drawable.pause);