-
-
Save kevinmcmahon/2988931 to your computer and use it in GitHub Desktop.
private boolean isServiceRunning() { | |
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); | |
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)){ | |
if("com.example.MyNeatoIntentService".equals(service.service.getClassName())) { | |
return true; | |
} | |
} | |
return false; | |
} |
Optimized with Kotlin language ...
@Suppress("DEPRECATION")
fun <T> Context.isServiceRunning(service: Class<T>): Boolean {
return (getSystemService(ACTIVITY_SERVICE) as ActivityManager)
.getRunningServices(Integer.MAX_VALUE)
.any { it -> it.service.className == service.name }
}
Thanks @oky2abbas!
Small style tweaks.
@Suppress("DEPRECATION") // Deprecated for third party Services.
fun <T> Context.isServiceRunning(service: Class<T>) =
(getSystemService(ACTIVITY_SERVICE) as ActivityManager)
.getRunningServices(Integer.MAX_VALUE)
.any { it.service.className == service.name }
getRunningServices is deprecated in API 30 any alternatives
getRunningServices is deprecated in API 30 any alternatives
ping pong with localbroadcaster
@MetinSeylan Not bad idea but it's standard ?
@oky2abbas good question, have you found another way to do it?
Thanks you
let me write it more kotlinish way :)
@Suppress("DEPRECATION") // Deprecated for third party Services.
inline fun <reified T> Context.isServiceRunning2() =
(getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager)
.getRunningServices(Integer.MAX_VALUE)
.any { it.service.className == T::class.java.name }
Does anyone know if it's possible to see if an activity/service of another app is currently active/in foreground?
Working with android 10 - making a launcher for another (older) app and have to be able to see if it's already running or not (so that I don't start it twice).
@MetinSeylan Can you describe more what you meant by ping pong with localbroadcaster or give some sample code for this?
@MetinSeylan Can you describe more what you meant by ping pong with localbroadcaster or give some sample code for this?
Send broadcast "PING", listen in service, if service is working, it will bring back "PONG" so that can indicate that service is running. If nothing is returned (you can set like 5s waiting period), this indicate that service is not running.
Store a boolean value in shared preferences, simple.