Before starting or stopping the service service, it is necessary to determine whether the service is running, decide whether to start or stop the service, and if it has been started before starting, it will cause unnecessary waste of system resources and not start before the end, which will cause the program to be abnormal. Here is a method that determines whether a service is running, an incoming parameter is the context of the activity that invokes the method, and the other is the full service name, including the package name.
1 Public Booleanisrunning (Context c,string serviceName)2 {3Activitymanager myam=(Activitymanager) C.getsystemservice (context.activity_service);4 5Arraylist<runningserviceinfo> runningservices = (arraylist<runningserviceinfo>) Myam.getrunningservices (40);6 //get up to 40 currently running services, put into the arrlist, to the current phone processing capacity, if more than 40 services, estimated to be dead, so do not consider more than 40 what to do7 for(inti = 0; I<runningservices.size (); i++)//Loop Enumeration Comparison8 {9 if(Runningservices.get (i). Service.getclassname (). toString (). Equals (ServiceName))Ten { One return true; A } - } - return false; the}