Android-determine whether the Service is enabled, and android determines the service
Continued the Baidu map positioning Demo, used the Service for Baidu positioning, and encountered a problem when uploading data to the server: after using the memory to close the program in the real machine, the Service will be closed, but in a few seconds, it will automatically restart; restart, and the same Service will be enabled when you log on to the system again, in LogCat, the location data is obtained twice each time. Then, you can determine whether the Service has been created before the Service is created? As long as we can make this judgment, we will ignore the existence of the Service. If it does not exist, we will create it. In this way, Baidu will find it feasible (it is best to determine whether the Service backend Service exists when it is created ), the Code is as follows:
private boolean isWorked(String className) {ActivityManager myManager = (ActivityManager) LoginActivity.this.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager.getRunningServices(30);for (int i = 0; i < runningService.size(); i++) {if (runningService.get(i).service.getClassName().toString().equals(className)) {return true;}}return false;}
Judgment process:
If (! This. isWorked ("package. service name ") {Intent intent = new Intent (); intent. setAction ("intent-filter action of the service component"); // start ServicestartService (intent);} else {Log. I ("info", "service started !! ");}
How does android determine whether the service has been stopped?
// Check whether the service is running
Private boolean isServiceRunning (Context context, String service_Name ){
ActivityManager manager =
(ActivityManager) context. getSystemService (Context. ACTIVITY_SERVICE );
For (RunningServiceInfo service: manager. getRunningServices (Integer. MAX_VALUE ))
{
If (service_Name.equals (service. service. getClassName ()))
{
Return true;
}
}
Return false;
}
Android determines whether the service is running
Before starting a Service, you should determine whether the Service is running or not. // This method determines your own Service --> com. android. controlAddFunctions. whether PhoneService has run public static boolean isWorked () {ActivityManager myManager = (ActivityManager) context. getSystemService (Co ntext. ACTIVITY_SERVICE); ArrayList <RunningServiceInfo> runningService = (ArrayList <RunningServi ceInfo>) myManager. getRunningServices (30); for (int I = 0; I <runningService. size (); I ++) {if (runningService. get (I ). service. getClassName (). toString (). equals ("c om. android. controlAddFunctions. phoneService ") {return true ;}} return false ;}