NotificationListenerService无法连接到通知管理器。

3
我遇到了一些问题,无法创建一个扩展android.service.notification.NotificationListenerService的服务。
根据https://developer.android.com/reference/android/service/notification/NotificationListenerService.html的说明,我已经在清单文件中添加了以下内容:
<service android:name=".NotificationListener"
 android:label="@string/service_name"
 android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
        <intent-filter>
            <action android:name="android.service.notification.NotificationListenerService" />
        </intent-filter>
</service>

我重写了 Service#onStartCommand 方法:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "Got onStartCommand");
    return super.onStartCommand(intent, flags, startId);
}

并且 NotificationListenerService#onListenerConnected:

@Override
public void onListenerConnected() {
    Log.d(TAG, "Got onListenerConnected");
}

当我使用显式意图启动服务时,尽管我看到onStartCommand运行但没有看到onListenerConnected。如果我尝试从onStartCommand中运行requestInterruptionFilter(NotificationListenerService.INTERRUPTION_FILTER_NONE)(这是我想要做的),我会收到W/NotificationListenerService[NotificationListener]: Notification listener service not yet bound.的错误信息。
你有什么想法为什么我没有得到onListenerConnected()(因此无法发送requestInterruptionFilter)?
这是在Xperia Z1 compact上运行的Lollipop 5.1.1。
4个回答

6
  1. 打开设置应用
  2. 声音和通知
  3. 通知访问
  4. 在此屏幕上应列出您的服务名称。
  5. 选中您的服务名称旁边的复选标记。

Android 5.1 Notification access

Android 5.1 通知访问截图


2
您可以通过以下方式编程检查您的应用程序是否被授予权限:
String notificationListenerString = Settings.Secure.getString(this.getContentResolver(),"enabled_notification_listeners");
//Check notifications access permission
if (notificationListenerString == null || !notificationListenerString.contains(getPackageName())) {
    //The notification access has not acquired yet!
    Log.d(TAG, "no access");
    requestPermission();
}
else {
    //Your application has access to the notifications
    Log.d(TAG, "has access");
}

你可以设置通知来提示用户使用requestPermission()启用通知权限。
public void requestPermission() {
    Intent requestIntent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
    requestIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(requestIntent);
}

2
为了正确工作,您应该在手机设置中授予通知访问权限。
此设置位于:
设置 > 隐私 > 特殊权限 > 通知访问。
只需在设置中搜索“通知访问”即可。
您可以使用此意图:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1)
    startActivity(Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS))
else
    startActivity(Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"))

在列表中检查您的应用程序名称。


2

用户必须明确允许您的应用程序监听通知。这将授予您的服务运行和接收回调的权限。没有其他途径。

您需要在“设置”应用程序中找到该选项。


我在清单文件中有 <uses-permission android:name="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"/>,这不够吗?还有其他权限可以“允许用户监听通知”吗? - CharleyGC
1
仅仅因为你请求了权限并不意味着你就能够听到它。如果你读完我帖子中的最后一句话,它会指引你朝正确的方向前进。 - JoxTraex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接