Check whether the service is enabled in Android

Source: Internet
Author: User

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>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.