android - To communicate with Service, what is the different between bindService() and create a instance of service? -


to communicate service, different between bindservice() , create instance of service? why should need use bindservice() communicate service? confused it.

(1)

public class bleservice extends service {     private static bleservice sservice;      @override     public void oncreate() {        super.oncreate();        sservice = this;     }      public static bleservice getinstance() {         return sservice;     } }  public class heartrateactivity extends activity {     private bleservice mbleservice;      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         mbleservice = bleservice.getinstance();     } } 

(2)

 public class bleservice extends service {     private final ibinder mbinder = new localbinder();     private bleservice mbleservice;      public class localbinder extends binder {       public myleservice getserverinstance() {           return myleservice.this;       }     } }  public class heartrateactivity extends activity {     private bleservice mbleservice;     private boolean mbounded;      @override     protected void onstart() {         super.onstart();          intent mintent = new intent(this, bleservice.class);         bindservice(mintent, mconnection, bind_auto_create);     }      serviceconnection mconnection = new serviceconnection() {         public void onservicedisconnected(componentname name) {             mbounded = false;             mbleservice = null;         }          public void onserviceconnected(componentname name, ibinder service) {             mbounded = true;             localbinder mlocalbinder = (localbinder)service;             mbleservice = mlocalbinder.getserverinstance();           }     };  } 

thanks

edit: remove new operator in oncreate() of service

you not instantiate service object via constructor using new keyword. service intended long-running process not tied lifetime of activity wants access it. such, services use intent signal android wish run them in same way use intent objects signal wish start new activity.

using .bindservice() can signal android want attach running service (and implicitly start service if isn't running already). once bound, can communicate service via whichever interfaces has available.


Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -