We would like to know how to checks if the specified service is currently running or not.
We can check if a service is running by service name.
The following code gets the list of RunningServiceInfo
and check its name one by one
to see if a service is running.
import java.util.List; //from ww w . j a v a 2s .com import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.app.Service; import android.content.Context; public class Main { /** * Checks if the specified service is currently running or not. * @param context * @param service * @param maxCheckCount * @return */ public static final boolean isServiceRunning(Context context, Class<? extends Service> service, int maxCheckCount) { if (context == null || service == null) { return false; } ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<RunningServiceInfo> list = manager.getRunningServices(maxCheckCount); for (RunningServiceInfo info : list) { if (service.getCanonicalName().equals(info.service.getClassName())) { return true; } } return false; } }