Android 为什么此NotificationListenerService不工作

Android 为什么此NotificationListenerService不工作,android,android-notifications,Android,Android Notifications,我在和NotificationListener服务抗争,运气不好。 我尝试了很多在这里和那里找到的食谱,特别是在。。。但它的工作原理却很不一致 首先看一下代码: 舱单: <service android:name=".services.NLService" android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" > <intent-filter>

我在和NotificationListener服务抗争,运气不好。 我尝试了很多在这里和那里找到的食谱,特别是在。。。但它的工作原理却很不一致

首先看一下代码:

舱单:

<service
    android:name=".services.NLService"
    android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" >
    <intent-filter>
        <action android:name="android.service.notification.NotificationListenerService" />
    </intent-filter>
</service>
在主活动中启动服务,或者我们要求用户在需要时启用设置:

if (!Utilities.hasNotificationAccess(this)) 
{
     Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
     startActivity(intent);
     Log.i(TAG,"hasNotificationAccess NO");
}
else
{
    Log.i(TAG,"hasNotificationAccess YES");

    // without this startService, it never works with Android 4.4...
    // but this is not needed in Android 6... 
    Intent mServiceIntent = new Intent(this, NLService.class);
    startService(mServiceIntent);
}
显然,已启用通知的安全访问设置

在Android 6上:

在NLService本身上,onBind和onUnbind方法的添加使其工作,我可以使用onBind日志,并且onNotificationPosted被很好地触发。但它会一直持续到下一次启动应用程序,然后再也没有绑定,再也没有onNotificationPosted,只是在我返回安全设置以取消选中“重新检查通知访问”之前什么都不会发生:在生产环境中,每次启动应用程序时都重复此操作是不可能的

在Android 4.4上:

与安卓6不同的是,在MainActivity中,我需要显式启动NLService,否则它永远不会自行统计。但是,它再次适用于第一次启动,并且在取消选中“重新检查安全设置”之前不会再次工作


我错过了什么明显的东西吗

Android缓存存在问题。在设备上上载应用程序时,操作系统会将您的服务连接到Notification Manager。如果您以前运行过应用程序,Android会在缓存中找到此服务,因此不会重新连接

解决方法:在将应用程序推送到您的设备上之前,请重命名您的服务(Android Studio中的重构选项工作得很好)-Android会将此服务识别为新服务并连接到Notification Manager


-连接到Notification Manager后将调用此方法,以便您可以检查您的服务是否已连接。

您好,找到根本原因了吗?我遇到了同样的问题,不知道如何解决。我发现原因是在设备上重新编译应用程序:首先编译,允许设置,它可以工作。第二个编译:除非重新检查或重新启动手机,否则无法工作。然而,这是一个测试环境问题,看起来没有这样的问题,当你简单地重新启动应用程序而不重新编译时,设置仍然有效。。。我不知道为什么它在重新编译时丢失了。。。希望他能帮助你@JBA我在oreo设备中也面临同样的问题。你能帮我解决这个问题吗?这是一个很好的解决方法,并解释了这个问题!您是成功地创建了某种“自动”服务动态随机名称,还是每次迭代都手动执行此操作?不,每次都是手动执行。我还发现了一段应该重新加载此服务的代码,但它对我不起作用->我在Android 7.0上使用Nexus 5,使用minSdkVersion 18和compileSdkVersion 24编译。当我上传到playstore上时,这种解决方法是否有效?我还没有尝试过。当我在寻找这个解决方案时,有人说通过Play store进行的更新不会导致这个问题。根据这些信息,应用这个变通方法应该是没有必要的(但我找不到证明它的链接)。
if (!Utilities.hasNotificationAccess(this)) 
{
     Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
     startActivity(intent);
     Log.i(TAG,"hasNotificationAccess NO");
}
else
{
    Log.i(TAG,"hasNotificationAccess YES");

    // without this startService, it never works with Android 4.4...
    // but this is not needed in Android 6... 
    Intent mServiceIntent = new Intent(this, NLService.class);
    startService(mServiceIntent);
}