Reputation: 896
This is a known bug.
NotificationListenerService gets killed during app updates and sometimes even randomly and it isn't restarted automatically. Further, it can't even be started manually but we have to prompt the user to reboot the device, since the service only seems to be able to be started on device boot.
The following doesn't work (trying to start the service manually):
startService(new Intent(this, NotificationService.class));
Are there any workarounds for this? I need the service to be constantly running and getting the OnNotificationPosted events.
Upvotes: 3
Views: 3148
Reputation: 1
Solved,
Set the notificationListenerServer to be foreground service. Then the service would be alive.
createNotificationChannel(); startForeground(NOTIFICATION_ID, getNotification());
Upvotes: 0
Reputation: 902
Do you try setting START_STICKY
?
More information about it: https://developer.android.com/reference/android/app/Service.html#START_STICKY
May be my answer can help you too. Please take a look at https://stackoverflow.com/a/35435065/1554094
Upvotes: 1
Reputation: 667
Try this code to manually disable & re-enable the service
private void toggleNotificationListenerService() {
PackageManager pm = getPackageManager();
pm.setComponentEnabledSetting(new ComponentName(this, your.NotificationListenerServiceImpl.class), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
pm.setComponentEnabledSetting(new ComponentName(this, your.NotificationListenerServiceImpl.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
}
You can catch the broadcast Intent.ACTION_PACKAGE_CHANGED
to know when the service gets disabled.
And you can use this code to check if your notification service is enabled.
private static boolean isNotificationListenerServiceEnabled(Context context) {
Set<String> packageNames = NotificationManagerCompat.getEnabledListenerPackages(context);
if (packageNames.contains(context.getPackageName())) {
return true;
}
return false;
}
Upvotes: 0
Reputation: 2121
This might not solve your problem completely but it might help with the service being killed randomly. I had a similar problem with my own app. Although I worked around the problem in another way, I found out about foreground services.
Apparently, Android kills your notification service to save memory and that explains the seemingly random kills.
To work around this, you can use a foreground service that will not be killed by Android and the service will be running at all times. See Running a Service on Foreground.
Upvotes: 1