2015-11-06 81 views
2

我无法创建延伸android.service.notification.NotificationListenerServiceNotificationListenerService没有连接到通知管理器

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); 
} 

and NotificationListenerService#onListenerConnected

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

当我运行,虽然开始明确的意图服务,我看到,onStartCommand运行,但不是onListenerConnected。如果我尝试运行requestInterruptionFilter(NotificationListenerService.INTERRUPTION_FILTER_NONE),从onStartCommand(这是我想做的事情)我得到W/NotificationListenerService[NotificationListener]: Notification listener service not yet bound.

任何想法,为什么我没有得到onListenerConnected()(因此不能发送requestInterruptionFilter)?

这是关于Xperia Z1 compact的Lollipop 5.1.1。

+0

对此有何好运? – user1163234

回答

1

您的应用必须明确地由用户allowef来收听通知。这将授予您的服务运行和接收回调。没有其他办法了。

您需要在设置应用程序的某处找到该选项。

+0

我在清单中有'<使用权限android:name =“android.permission.BIND_NOTIFICATION_LISTENER_SERVICE”/>',这不够吗?是否有另一个'允许用户收听通知'的权限? – CharleyGC

+1

只是因为您请求的权限不会授予您可以听取它的权限。如果您阅读我的文章中的最后一句,它会指出您正确的方向。 – JoxTraex

0
  1. 打开设置应用
  2. 声音&通知
  3. 通知接入
  4. 您的服务名称应该在此界面中列出。
  5. 检查您的服务名称旁边的标记

Android 5.1 Notification access

的是Android 5.1的通知接入截图

0

您可以通过编程检查,如果您的应用程序给出以下权限:

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"); 
} 

然后,您可以设置通知以指示用户启用通知权限with requestPermission()

public void requestPermission() { 
    Intent requestIntent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"); 
    requestIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    startActivity(requestIntent); 
}