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

半世苍凉 提交于 2019-12-19 06:41:29

问题


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)


回答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

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

}


来源:https://stackoverflow.com/questions/48506971/how-to-check-if-a-service-is-running-on-android-8-api-26

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