Generally, startservice (intent service) is used to start a service. However, in this case, the reference of the service object cannot be obtained. You can enable the service through the bindservice method. The following is a small example:
1. Caller
Package COM. zhf. local; import android. app. activity; import android. content. componentname; import android. content. context; import android. content. intent; import android. content. serviceconnection; import android. OS. bundle; import android. OS. ibinder;/*** the purpose of this example is to get the reference of myservice, the internal method and variable * @ author administrator **/public class localserviceactivity extends activity {/** called when the activity is first created. */private myservice; @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); intent = new intent (this, myservice. class); bindservice (intent, connection, context. bind_auto_create);} private serviceconnection connection = new serviceconnection () {@ overridepublic void onservicedisconnected (componentname) {myservice = NULL;} @ overridepublic void onserviceconnected (componentname, ibinder Service) {myservice = (myservice. mybinder) Service ). getservice (); system. out. println ("service connection successful"); // execute the internal method myservice of the service. excute () ;}}; protected void ondestroy () {super. ondestroy (); unbindservice (connection );};}
2. Service Provider
Package COM. zhf. local; import android. app. service; import android. content. intent; import android. OS. binder; import android. OS. ibinder; public class myservice extends Service {private final ibinder binder = new mybinder (); @ overridepublic ibinder onbind (intent) {return binder ;} public class mybinder extends binder {myservice getservice () {return myservice. this ;}} public void excute () {system. out. println ("using binder to get service reference to call internal service method");} @ overridepublic void ondestroy () {// when the caller exits (even if unbindservice is not called) or the super. ondestroy () ;}@ overridepublic Boolean onunbind (intent) {// system is called when the caller exits (even if unbindservice is not called) or stops the service. out. println ("the caller has exited"); return Super. onunbind (intent );}}