I would like to share my answer because of the information that I have gathered from various topics in stackoverflow and my own tests. If your NotificationListenerService does not work (exception, for example IllegalStateException), the system will kill it and not restore it again. You can see that in logcat:
592-592/? E/NotificationService﹕ unable to notify listener (posted): android.service.notification.INotificationListener$Stub$Proxy@42 91d008 android.os.DeadObjectException ....
If the user goes to "Security", "Notifications", disables and enables your application, it still does not work. What for? Since it will only restart if the user reboots the phone, or if the user re-enables the BUT> option passing through your application using:
startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
So, we need to check two things: first, if the option is enabled:
private boolean checkNotificationSetting() { ContentResolver contentResolver = getContentResolver(); String enabledNotificationListeners = Settings.Secure.getString(contentResolver, "enabled_notification_listeners"); String packageName = getPackageName(); return !(enabledNotificationListeners == null || !enabledNotificationListeners.contains(packageName)); }
If it is turned on, we check if the service is Death:
private boolean isNLServiceCrashed() { ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningServiceInfo> runningServiceInfos = manager.getRunningServices(Integer.MAX_VALUE); if (runningServiceInfos != null) { for (ActivityManager.RunningServiceInfo service : runningServiceInfos) { //NotificationListener.class is the name of my class (the one that has to extend from NotificationListenerService) if (NotificationListener.class.getName().equals(service.service.getClassName())) { if (service.crashCount > 0) { // in this situation we know that the notification listener service is not working for the app return true; } return false; } } } return false; }
What is this service.crashCount ? The documentation reads:
The number of times the service process crashed while the service was running.
So, if it is more than 0, then this is death. Therefore, in both cases, we must warn the user and offer the ability to restart the service using the intention that I published earlier:
startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
Of course, if the service crashes, it will be useful to determine why and when to prevent it.