我在创建扩展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
。如果我尝试从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 :(得分:3)
答案 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 :(得分:1)
您的应用必须由用户明确地允许听取通知。这将授予您的服务运行和接收回调。没有其他办法了。
您需要在“设置”应用中找到该选项。