Pavel Machala Pavel Machala - 3 months ago 11
Android Question

Android - avoiding parallel run of same service within multiple apps

Little background: I am developing library which uses one background service. There is a hight probability that there will be 2 or more apps implementing the library on the same android phone.

Q: Is there any solution to prevent this background service from running if one of the installed apps already launched the service? I basically need only one instance of that bg service running no matter how many apps is implementing the lib with service.


So later on I realized that I can list all running services and match the names to service I am interested in. And if it is running then I won't try to launch another one.

protected static boolean isMyServiceRunning(Class<?> serviceClass, Context cont) {
    ActivityManager manager = (ActivityManager) cont.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningServiceInfo> list = manager

    if (list == null || list.isEmpty()) {
        return true;
    for (ActivityManager.RunningServiceInfo service : list) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
    return false;

The method will return true if it finds the service running. Also you can list only specific amount of services using getRunningServiceInfo(x).