使用PendingIntent.getService的startForeground错误通知?

时间:2014-11-10 00:06:22

标签: java android android-notifications

我不时得到:

android.app.RemoteServiceException: Bad notification for startForeground:
java.lang.NullPointerException

但仅限于Android 4.3。在Android Kitkat或Lollipop上,它按预期工作。只有当我像这样使用PendingIntent.getService时,问题才会存在:

Intent rewindIntent = new Intent(AudioPlayerService.this, AudioPlayerService.class);
PendingIntent rewindPI = PendingIntent.getService(
    AudioPlayerService.this, 0, rewindIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.addAction(R.drawable.ic_fast_rewind_grey600_36dp, null, rewindPI);

但是当我改为使用

Intent i = new Intent("pause");
PendingIntent pauseActionPI = PendingIntent.getBroadcast(
    getApplicationContext(), 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
builder.addAction(R.drawable.av_pause_dark, "Pause", pauseActionPI);

它适用于所有版本的android。为什么会这样?我做错了什么?

您可以看到完整的源代码here和之前的工作版here

2 个答案:

答案 0 :(得分:4)

好的,看似永远,我找到了解决方案。问题是,如果你设置一个像

这样的动作
Notification.Action action = new Notification.Action(R.drawable.av_pause_dark, null, pendingIntent);

它会在Android 4.3版本上崩溃,但在其他版本上也能正常运行。

关键是,您必须定义显示的文本。如果你想没有文字(比如我),你必须把它设置为

Notification.Action action = new Notification.Action(R.drawable.av_pause_dark, "", pendingIntent);

所以诀窍是设置""而不是null

答案 1 :(得分:0)

使用构建器设置图标,并仔细检查documentation

必填通知内容

A Notification object must contain the following:

 - A small icon, set by setSmallIcon() 
 - A title, set by setContentTitle()
 - Detail text, set by setContentText()
相关问题