我有一个媒体服务,它使用 startForeground() 在播放开始时显示通知。播放时有暂停/停止按钮,暂停时有播放/停止按钮。
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
// setup...
Notification n = mBuilder.build();
if (state == State.Playing) {
startForeground(mId, n);
}
else {
stopForeground(false);
mNotificationManager.notify(mId, n);
}
这里的问题是当我显示/更新处于暂停状态的通知时,应该允许您将其删除。mBuilder.setOngoing(false)
似乎没有效果,因为以前的startForeground
覆盖它。
stopForeground(true);
使用相同的代码调用按预期工作,但通知会在它被销毁和重新创建时闪烁。有没有办法“更新”从 startForeground 创建的通知以允许在调用 stop 后将其删除?
编辑:根据要求,这是创建通知的完整代码。每当播放或暂停服务时都会调用 createNotification。
private void createNotification() {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("No Agenda")
.setContentText("Live stream");
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{
if (state == State.Playing) {
Intent pauseIntent = new Intent(this, MusicService.class);
pauseIntent.setAction(ACTION_PAUSE);
PendingIntent pausePendingIntent = PendingIntent.getService(MusicService.this, 0, pauseIntent, 0);
mBuilder.addAction(R.drawable.pause, "Pause", pausePendingIntent);
//mBuilder.setOngoing(true);
}
else if (state == State.Paused) {
Intent pauseIntent = new Intent(this, MusicService.class);
pauseIntent.setAction(ACTION_PAUSE);
PendingIntent pausePendingIntent = PendingIntent.getService(MusicService.this, 0, pauseIntent, 0);
mBuilder.addAction(R.drawable.play, "Play", pausePendingIntent);
mBuilder.setOngoing(false);
}
Intent stopIntent = new Intent(this, MusicService.class);
stopIntent.setAction(ACTION_STOP);
PendingIntent stopPendingIntent = PendingIntent.getService(MusicService.this, 0, stopIntent, 0);
setNotificationPendingIntent(mBuilder);
mBuilder.addAction(R.drawable.stop, "Stop", stopPendingIntent);
}
else
{
Intent resultIntent = new Intent(this, MainActivity.class);
PendingIntent intent = PendingIntent.getActivity(this, 0, resultIntent, 0);
mBuilder.setContentIntent(intent);
}
Notification n = mBuilder.build();
if (state == State.Playing) {
startForeground(mId, n);
}
else {
stopForeground(true);
mNotificationManager.notify(mId, n);
}
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void setNotificationPendingIntent(NotificationCompat.Builder mBuilder) {
Intent resultIntent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
}
后续编辑:
下面的评论之一提到答案可能是“脆弱的”,而随着 Android 4.3 的发布,背后的行为startForeground
已经发生了变化。startForeground 将强制您的应用程序在前台显示通知,并且应该只调用该方法并显示通知。我尚未测试,但接受的答案可能不再按预期工作。
在调用时停止闪烁方面stopForeground
,我认为不值得为框架而战。
这里有一些关于 Android 4.3 通知更改的附加信息。