Home > other >  Android Location foreground service calling
Android Location foreground service calling

Time:12-27

I am using android foreground service for continuous location updates that starts when user clicks a button. My question is what if the user presses the button twice? Will there be two foreground process running? If so, how to check whether foregroundservice running already or not.

So that I can apply a condition before calling the foreground service. Please let me know if there a way.

CodePudding user response:

Services are singletons- only one will exist at a time. However, it will call onStartCommand again with a new Intent if you call startService or startForegroundService again. So make sure that call won't cause you to rerequest location updates if you already have.

CodePudding user response:

You can check if your service is running or not by using this function:

private fun isMyServiceRunning(serviceClass: Class<*>): Boolean {
        val manager = getSystemService(ACTIVITY_SERVICE) as ActivityManager
        for (service in manager.getRunningServices(Int.MAX_VALUE)) {
            if (serviceClass.name == service.service.className) {
                return true
            }
        }
        return false
    }

If your service is not running start the service:

if (!isMyServiceRunning(MyService::class.java) {
    startService(...)
}
  • Related