Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a service is running on Android 8 (API 26)?

I had some functionalities of my app broken once upgrading to Android 8, even not targeting the API 26 explicitly. In particular, the good old function to check if a Service is running (as documented on StackOverflow here: How to check if a service is running on Android?) is not working anymore.

Just to refresh our collective memory, it was this classic method:

private boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

The problem now is that getRunningServices is now deprecated and doesn't return the running services anymore. Does anyone have experience with this issue on Android 8? Is there any official solution (or hack) available? I should also point out that the Service I want to look for is not in the same process/app as the code that is calling isMyServiceRunning() (that functionality is still provided for backward compatibility reasons)

like image 952
Enrico Casini Avatar asked Jan 29 '18 17:01

Enrico Casini


1 Answers

getRunningServices() this method is no longer available to third party applications. there's no substitute method for getting the running service.

https://developer.android.com/reference/android/app/ActivityManager.html#getRunningServices(int)

How to check if a service is running on Android?) I just check it manually , I put Boolean true when service is running and false when the service stopped or destroyed. I'm using SharedPreferences to save the Boolean value.

Service.class

override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
    Log.d("service", "onStartCommand")
    setRunning(true)
}

private fun setRunning(running: Boolean) {
    val sessionManager = SessionManager(this)
    sessionManager.isRunning = running
}


override fun onDestroy() {
   setRunning(false)
   super.onDestroy()
}

SessionManager.class

class SessionManager(var context: Context) {
    private val loginpreferences: SharedPreferences
    private val logineditor: SharedPreferences.Editor

    init {
      loginpreferences = context.getSharedPreferences(Pref_name, private_modde)
      logineditor = loginpreferences.edit()
    }

    var isRunning: Boolean
      get() = loginpreferences.getBoolean(SERVICES, false)
      set(value) {
         logineditor.putBoolean(SERVICES, value)
         logineditor.commit()
      }

    companion object {
      private val SERVICES = "service"
    }

}
like image 187
Exel Staderlin Avatar answered Sep 21 '22 08:09

Exel Staderlin