我有一个媒体服务,使用startForeground()在播放开始时显示通知。当播放时,它有暂停/停止按钮;当暂停时,它有播放/停止按钮。
我有一个媒体服务,使用 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
时停止闪烁,我认为不值得与框架抗争。
setOngoing(false)
时展示你的代码吗?我怀疑通知没有被重建以获取更改,但从这个片段很难判断。 - dsandler