android - StartForeground 错误通知错误

标签 android notifications android-service

我正在尝试使用 while 循环来每秒更新一次通知。然而,在 2.3.3 及以下版本中,它会因以下 logcat 错误而崩溃:

08-14 07:30:17.394: E/AndroidRuntime(501): FATAL EXCEPTION: main
08-14 07:30:17.394: E/AndroidRuntime(501): 
android.app.RemoteServiceException: Bad notification for startForeground: 
java.lang.IllegalArgumentException: contentIntent required: 
pkg=com.package.name id=77 
notification=Notification(vibrate=null,sound=null,defaults=0x4,flags=0x40)

问题是,即使当我检查 Build.VERSION 时,代码也会崩溃并出现相同的 logcat 错误:

if (isRunning) {
        n.defaults = Notification.DEFAULT_LIGHTS;
        while (!RecordTimerTask.isRunning && isRunning) {
            long now = System.currentTimeMillis() - startTime;
            n.setLatestEventInfo(getApplicationContext(), getResources()
                    .getString(R.string.notify_title),
                    getDurationBreakdown(now), null);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                startForeground(FOREGROUND_ID, n);
            else 
                notify.notify(ID, n);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

运行 2.3.3 及以下版本的设备似乎不喜欢空通知 Intent 。 我不明白的是,为什么在从未调用 startForeground 时会收到有关 startForeground 的 logcat 错误?

最佳答案

问题是您调用 setLatestEventInfo 时,pendingIntent 的参数为空。这适用于 Android ICS,但不适用于早期版本...

查看 setLatestEventInfo 的文档

您的代码应如下所示(如果您从服务推送这些通知):

        // The PendingIntent to launch our activity if the user selects this notification
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, LocalServiceActivities.Controller.class), 0);

    // Set the info for the views that show in the notification panel.
    notification.setLatestEventInfo(this, getText(R.string.local_service_label),
                   text, contentIntent);

代码引用自Android official documentation .

另请参阅this StackOverflow 上的类似问题。

关于android - StartForeground 错误通知错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11947928/

相关文章:

android - Android 中的倾斜或倾斜 UI 设计

notifications - 更改applescript中的通知图标

java - 在 Android 中后台访问麦克风

android - 如何从服务调用 Activity 中的方法

android - 如何在android中检测长按音量按钮

java - 如何在android中设置日历中日期的颜色

android - 高度和阴影错误的工具栏

android - 通知收件箱样式会在收到通知时更新

ios - 使用两个委托(delegate)

android - 解析所有匹配 Intent 过滤器的服务