Check whether the service is enabled in Android
This is what I learned yesterday. Let's make a summary.
Check whether the service is enabled and you need to write a tool class for ease of use. Pass the service name to return a Boolean value. Of course, a context is required.
Let's talk about the key points of this tool class:
1. The method must be set to context and serviceName. context is used to getSystemService () to obtain ActivityManager. Note: This method parameter must use the Context. ACTIVITY_SERVICE parameter in upper case. Otherwise, an error may occur. If you do not know what the error is, it takes me 10 minutes to know. Remember this.
2. The ActivityManager instance can use the getRunningService () method. The parameter is used to obtain the maximum number of services, which is generally 100.
3. The List returned by the above method is to traverse it and get the name of each service. In comparison, the result is returned.
The following is the specific code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
Import java. util. List; Import android. app. ActivityManager; Import android. app. ActivityManager. RunningServiceInfo; Import android. app. Service; Import android. content. Context; Public class ServiceStateUtiles { Public static Boolean isServiceRunning (Context context, String serviceName ){ // Obtain the service method parameters in uppercase !!! ActivityManager am = (ActivityManager) context. getSystemService (Context. ACTIVITY_SERVICE ); List <runningserviceinfo> infos = am. getRunningServices (100 ); For (RunningServiceInfo info: infos ){ String className = info. service. getClassName (); If (serviceName. equals (className )) Return true; } Return false; } } </Runningserviceinfo> |