Android foreground service not restarted once stopped
Closed this issue · 2 comments
Describe the bug
When the foreground service is stopped (e.g. when all watchers are removed), the service is not started again upon adding a watcher as the service type is no longer FOREGROUND_SERVICE_TYPE_NONE
but FOREGROUND_SERVICE_TYPE_LOCATION
. The issue seems to be this check which due to the last condition does prevent the foreground service from being started again:
// Promote the service to the foreground if necessary.
if (backgroundNotification != null && (
// Unfortunately, 'getForegroundServiceType' was only introduced in API level 29.
// However, it appears that 'startForeground' is idempotent, so for older Androids
// we just call it repeatedly each time a background watcher is added.
Build.VERSION.SDK_INT < Build.VERSION_CODES.Q
|| getForegroundServiceType() == ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE //<-- THIS CAUSES THE ISSUE
)) {
To Reproduce
Steps to reproduce the behavior:
- Start a watcher --> notification shown
- Remove the watcher --> notification removed
- Start another watcher --> no notification shown
Expected behavior
Foreground service should be started if it is not running.
Additional context
Tested with Galaxy Tab S7, Android 13 and Fairphone 4, Android 13
Workaround
Remove old watcher only when new watcher was added, so that foreground service is never stopped (e.g. setTimeout(..., 3000)
)
Potential fix
Adding another condition getForegroundServiceType() == ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION
worked fine for me. The foreground service is simply stopped and started again with the notification dis/reappearing within less than a second.
I've removed the check entirely. Please test v1.2.19.
Thanks! Seems to do the job.