我将尝试提供我使用过的解决方案,并且大多数音乐播放器也使用相同的技术在通知栏中显示播放器控件。
我正在运行一项用于管理媒体播放器及其所有控件的服务。 Activity 用户控件通过向服务发送 Intent 与服务交互,例如
Intent i = new Intent(MainActivity.this, MyRadioService.class);
i.setAction(Constants.Player.ACTION_PAUSE);
startService(i);
为了在 Service 类中接收意图并执行操作,我在 Service 的 onStartCommand 方法中使用以下代码
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(Constants.Player.ACTION_PAUSE)) {
if(mediaPlayer.isPlaying()) {
pauseAudio();
}
}
现在要准确回答您的问题,以显示带有播放控件的通知。您可以调用以下方法来显示带有控件的通知。
// showNotification
private void startAppInForeground() {
// Start Service in Foreground
// Using RemoteViews to bind custom layouts into Notification
RemoteViews views = new RemoteViews(getPackageName(),
R.layout.notification_status_bar);
// Define play control intent
Intent playIntent = new Intent(this, MyRadioService.class);
playIntent.setAction(Constants.Player.ACTION_PLAY);
// Use the above play intent to set into PendingIntent
PendingIntent pplayIntent = PendingIntent.getService(this, 0,
playIntent, 0);
// binding play button from layout to pending play intent defined above
views.setOnClickPendingIntent(R.id.status_bar_play, pplayIntent);
views.setImageViewResource(R.id.status_bar_play,
R.drawable.status_bg);
Notification status = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
status = new Notification.Builder(this).build();
}
status.flags = Notification.FLAG_ONGOING_EVENT;
status.icon = R.mipmap.ic_launcher;
status.contentIntent = pendingIntent;
startForeground(Constants.FOREGROUND_SERVICE, status);
}
希望这真的对你有帮助。你将能够实现你想要的。有一个快乐的编码:)