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

回眸只為那壹抹淺笑 提交于 2019-12-01 04:45:28

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"
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!