Reputation: 642
I have a sensor which connects with my app via bluetooth. I have created a Foreground service which keeps the app active and connected with the sensor even after user close the app. To stop the Foreground service, user relaunch the app and stops the foreground service.
All the above is done perfectly and works fine for NOW.
My problems are -
There is a play and pause button to start and stop the service. Once started, the icons changes but relaunching the app after closing the app completely (without stopping the foreground service), app doesn't change. Of course it doesn't change because I have no idea how to check if service is still running in the foreground or not.
Yes, I have read all the previous answers and most of them are either deprecated or doesn't work anymore.
Since Commonsware is asking for the link for all the posts I have read so far, here you go -
Upvotes: 2
Views: 2960
Reputation: 304
I found a really dirty workaround to check it, but it works. I would prefer to leave with the problem of inconsistency on UI and I didn't use it in my case, because I have switch instead of buttons, and switch can be easily changed by the user.
In my case, the foreground service is running alongside with notification, so there is a possibility to check notification status rather than foreground service status.
var isServiceRunning = false;
val manager = getSystemService(NotificationManager::class.java)
for (notification in manager.activeNotifications){
if (notification.notification.channelId == "ServiceChannel") {
isServiceRunning = true;
break;
}
}
Upvotes: 2
Reputation: 134
Try this Util to check if service is running:
public static boolean isServiceRunning(Context context, Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
Upvotes: 1