0

My question is very simple. I have a foreground service that, when activated, runs indefinitely until the user stops it. In the I MainActivity, I need to know if the service is running or not (image if the user closes the app but the foreground service is still running, when he reenters the app, I need to know if the service is already running). Is it viable to have a companion object on the Service with a status variable so that I can access its status? Something like this:

@AndroidEntryPoint
class SomeForegroundService: Service() {

    companion object {
        var status = 0
    }
....

And then somewhere in my MainActivity...

SomeForegroundService.status == 1

Is this prone to memory leaks? Whats a better solution (not counting with checking every running system service)

André Nogueira
  • 3,363
  • 3
  • 10
  • 16

2 Answers2

0

You can use this method to check is service is running or not instead of static variable

// check and return true if service is running
private boolean isMyServiceRunning() {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (TrackingService.class.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

Edit :
If you don't want to check every service, you can register broadcast receiver in the service and it pings the activity.
Original Answer by : How to check if a service is running on Android? (answer by Ben H)

Nitish
  • 3,075
  • 3
  • 13
  • 28
0

What you need is to bind the service

https://developer.android.com/guide/components/bound-services

If you use bindService(intent, connection, 0) without the Context.BIND_AUTO_CREATE flag, it will only bind to existing service, and return false if the service does not exist.

Ricky Mo
  • 6,285
  • 1
  • 14
  • 30
  • [`bindService`](https://developer.android.com/reference/android/content/Context#bindService(android.content.Intent,%20android.content.ServiceConnection,%20int)) returns false only if binding fails (invalid service or missing permission). You are allowed to bind to a service that is not running but you will not receive `onServiceConnected()` callback until that service starts. I guess you can use that state (binding active but no service connected) to determine that service is not running. – Pawel Sep 08 '21 at 10:04