18

我有一个正在运行的服务,当它收到一条消息说它必须更改时,它会更新通知栏中的通知。

但是,当要更新通知时,有时会出现以下错误

java.lang.IllegalArgumentException: contentIntent required

这是我的代码:

变量设置


int icon = R.drawable.notification;
CharSequence tickerText = "Test";
long when = System.currentTimeMillis();
PendingIntent contentIntent;

Notification notification = new Notification(icon, tickerText, when);

NotificationManager mNotificationManager;

NotificationManager 创建


    String ns = Context.NOTIFICATION_SERVICE;
    mNotificationManager = (NotificationManager) getSystemService(ns);

通知创建


    Intent notificationIntent = new Intent(this, TestsApp.class);
    contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.flags |= Notification.FLAG_NO_CLEAR;
    notification.icon = R.drawable.notification3;
    notification.setLatestEventInfo(this, "Registering", "Test", contentIntent);
    mNotificationManager.notify(1, notification);

通知更新


    notification.icon = R.drawable.notification2;
    notification.setLatestEventInfo(getApplicationContext(), "Registered", "Test", contentIntent);
    mNotificationManager.notify(1, notification);   

所以我的 contentIntent 发生了一些事情,这对吗?

它在我的 Service 类的顶部声明为成员变量,除了上面显示的代码之外,它没有在代码中的任何其他地方使用,那么它在哪里可以重置为 null?

4

4 回答 4

15

您需要为通知设置 contentIntent。

在你的情况下:

notification.contentIntent = notificationIntent;

否则您将收到消息,通知的 contentIntent 为空,因为它没有设置。

文档在这里:http: //developer.android.com/reference/android/app/Notification.html#contentIntent

我在这里有一个小例子:http: //united-coders.com/nico-heid/show-progressbar-in-notification-area-like-google-does-when-downloading-from-android

于 2010-09-13T15:39:10.673 回答
3

我认为这是因为 Android OS 版本

2.3或更低版本,必须设置contentIntent,否则会得到这个Exception。

在我的项目中,我是这样写的:

 if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { 
     Intent intent = new Intent();
     PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0); 
     mNotification.contentIntent = contentIntent; 
 }

也许这可以帮助你!

于 2015-05-15T09:20:50.583 回答
2

在你的情况下

contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,0);

如果您想使用具有相同操作但具有不同附加功能的 Intent:

  1. requestCode默认值更改"0"

    getActivity(Context context, int requestCode, Intent intent, int flags)
    

像独特的东西

(int) System.currentTimeMillis();
notification.contentIntent = notificationIntent;

这两个步骤都是强制性的,因为:

  • 如果没有选项 1,选项 2 将不起作用。
  • 选项 1 将在没有 2 的情况下抛出 IllegalArgumentException。
于 2011-11-29T22:19:50.503 回答
0

就我而言,我有一个示例代码要做,需要创建一个通知,并且我还收到“需要 contentIntent”错误 - 谷歌把我带到了这个线程:D

这个问题的根源是我从示例代码中复制并粘贴到 eclipse 项目中的引用。当我删除“”并输入它们并解决问题时。也许这对某人有帮助。

这些是引用错误的来源: nb.setContentTitle("My first notification!"); nb.setContentText("你好");

于 2013-06-15T21:26:10.710 回答