java – Android – getRunningservices(ActivityManager) deprecated-ThrowExceptions

Exception or error:

I want to know MyService.java is working or not?

I create this method:

private boolean isServiceAlive(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

it works fine but manager.getRunningServices() is deprecated from API 26. So have we another good solution(method) to get a list of the services that are currently running?

How to solve:

Despite it doesn’t answer your question, I think you still can use this method for your own services:

For backwards compatibility, it will still return the caller’s own services.

If you’d just like to remove the deprecation warning, use @SuppressWarnings("deprecation")

###

Welcome to Android O

Another Annoying bug of android Oreo, there is just Deprecated annotation and there is no other way to do this. but maybe in the past android developers decide to create alternative function.

For now as Document says continue to use getRunningServices and use @SuppressWarnings("deprecation") above of your function to get rid of warning.

As of Build.VERSION_CODES.O, this method is no longer available to third party applications. For backwards compatibility, it will still return the caller’s own services.

###

Here’s what you do. If the services you are using are within your own application, just make a singleton that has a boolean variable for started or stopped. When the service starts, make sure to update that variable.

public class SingletonServiceManager {

    public static boolean isMyServiceRunning = false;

}

The above is literally all i use for a small singleton class, later, in some other class, where you want to know if the service is running…

if(SingletonServiceManager.isMyServiceRunning == true){
    // do something
}

You just have to manage where and when this value is updated. For instance, set it to true when you start the service (inside the service). Then, update the boolean to false when you stop the service (from inside the service)

Leave a Reply

Your email address will not be published. Required fields are marked *