How to determine if an Android Service is running in the foreground?

后端 未结 6 923
眼角桃花
眼角桃花 2020-11-29 04:31

I have a service which I believe to have running in the foreground, How do I check if my implementation is working?

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 05:22

    This worked for me in the Coinverse app for crypto news.

    It's is the most concise Kotlin solution. Thanks to Abbas Naqdi in this GitHub issue.

    @Suppress("DEPRECATION") // Deprecated for third party Services.
    fun  Context.isServiceRunning(service: Class) =
            (getSystemService(ACTIVITY_SERVICE) as ActivityManager)
                .getRunningServices(Integer.MAX_VALUE)
                .any { it.service.className == service.name }
    

提交回复
热议问题