2015-11-06 78 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); 
}