android--determine if service has been started

Source: Internet
Author: User

continuation of the Baidu map positioning of the demo, the use of service to Baidu positioning, and upload data to the server encountered a problem: in the real machine after using clean memory to close the program, the service will be closed, but in a few seconds, it will automatically restart; restart even if, And once again landing the system, will open a same service, in the Logcat will see every time to get to two times the location data. Then think about whether you can tell if the service has been created before you build it? As long as we can make this judgment, then the service exists we do not care about it, if it does not exist then create, in this way, Baidu found feasible (servicebackground services are best to determine whether the existence ), 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 (int.); 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 ("Action for intent-filter of the serviced Component");// Start Servicestartservice (intent);} ELSE{LOG.I ("info", "Service has been started!! ");}





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.