【问题标题】:NotificationListenerService: NullPointerException on getActiveNotificationsNotificationListenerService:getActiveNotifications 上的 NullPointerException
【发布时间】:2013-09-12 03:29:32
【问题描述】:

我正在尝试根据本教程在我的应用程序中实现 NotificationListenerService:http://www.kpbird.com/2013/07/android-notificationlistenerservice.html,但在调用 getActiveNotifications 时出现 NullPointerException。

Caused by: java.lang.NullPointerException
at android.os.Parcel.readException(Parcel.java:1437)
at android.os.Parcel.readException(Parcel.java:1385)


at android.app.INotificationManager$Stub$Proxy.getActiveNotificationsFromListener(INotificationManager.java:500)
at android.service.notification.NotificationListenerService.getActiveNotifications(NotificationListenerService.java:149)
at com.rootsoft.rsnotificationservice.RSNotificationService.activeNot(RSNotificationService.java:85)
at com.rootsoft.rsnotificationservice.RSNotificationService.access$0(RSNotificationService.java:81)
at com.rootsoft.rsnotificationservice.RSNotificationService$1.onReceive(RSNotificationService.java:105)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:763)
... 9 more

我正在向应该生成所有通知列表的服务发送广播:

private void activeNot () {
    List l = new List();
    l.Initialize();

    for (StatusBarNotification sbn : getActiveNotifications() ) { <---- Error happens here
        l.Add(sbn);
    }

    Log.i("B4A", "List created.");


    }
}

【问题讨论】:

  • @XverhelstX,我更新了答案以提供更好的解决方案。

标签: java android notifications


【解决方案1】:

不要在 onCreate 或 onBind 中直接调用 getActiveNotification 方法。因为onBind会调用super.onBind进行初始化,所以可以使用handler来替换。 这是我的演示: https://github.com/yihongyuelan/NotificationListenerServiceDemo

【讨论】:

    【解决方案2】:

    编辑:从那以后,我对此有了更多了解并开始工作!

    注意:首先,确保您已在 Android 设备的通知访问设置窗格中启用您的应用。

    到目前为止,我遇到了完全相同的问题。事实证明,覆盖onBind 是危险的。如果您确实覆盖了onBind,则必须返回与super.onBind(intent) 返回的相同的IBinder。如果您想返回您自己的自定义活页夹,请确保使用唯一的 Intent,并且仅在收到自定义 Intent 时返回您的自定义活页夹。

    @Override
    public IBinder onBind(Intent intent)
    {
        if (intent.getAction().equals("custom_intent"))
        {
            return customBinder;
        }
        else
        {
            return super.onBind(intent);
        }
    }
    

    一旦您授予它读取通知的权限,系统就会在您的服务上调用 onBind。如果您的 onBind 向系统返回自定义绑定器,系统将不会给您通知,并可能导致空指针或安全异常。

    希望这有帮助!

    【讨论】:

    • 您好,您的意思是您可以通过在答案中添加方法来避免问题的异常?
    • 是的!我们必须以系统和我们自己都可以使用的方式覆盖 onBind。系统需要来自 Android 内部的 dep 的特定 Binder,我们必须提供它。我们期望我们自己的自定义活页夹,因此我们检查我们的自定义意图并返回我们的自定义活页夹。
    • 今天,我认为你的方式并不完全正确。你需要Enable Notification in Notification Access
    • 很好的解决方案。另外一点... Android 在启动时或首次选中“启用通知”时绑定到您的服务。在实施您的 onBind 解决方案后,我需要取消选中/重新选中启用通知按钮以使绑定正常工作。
    • 很好的解决方案!修复我的 SecurityException 问题。
    【解决方案3】:

    当我尝试使用 startService() 启动服务时,它发生在我身上。我错了!当用户启用您的应用程序侦听通知时,系统会为您执行此操作

    【讨论】:

      猜你喜欢
      • 2013-04-21
      • 2014-03-18
      • 2019-10-24
      • 2016-03-26
      • 2012-10-03
      • 1970-01-01
      • 2013-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多