Skip to content Skip to sidebar Skip to footer

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 run

Solution 1:

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

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

privatefunsetRunning(running: Boolean) {
    val sessionManager = SessionManager(this)
    sessionManager.isRunning = running
}


overridefunonDestroy() {
   setRunning(false)
   super.onDestroy()
}

SessionManager.class

classSessionManager(var context: Context) {
    privateval loginpreferences: SharedPreferences
    privateval logineditor: SharedPreferences.Editor

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

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

    companionobject {
      privateval SERVICES = "service"
    }

}

Post a Comment for "How To Check If A Service Is Running On Android 8 (api 26)?"