Bound Services
CS architecture, where c is the calling component, S is bound Services;
C by Bindservice to bind, this method immediately return, no return value, C need to implement serviceconnection inside the onserviceconnected and onservicedisconnected interface.
When more than one C is bound to the same s, S is called only once Onbind returns IBinder, followed by the C that binds s, directly to get the same ibinder,onbind no longer repeated execution.
Create bound Services
- Extension Binder class: Services that are called only within the app are not invoked by other applications or across processes.
- Use Messenger:service to define handler to receive message,client send message. This is the simplest implementation of the IPC invocation, but the messenger queue handles all requests in one thread and cannot be multithreaded at the same time.
- With Aidl: If you are cross-process and need to process multiple requests at the same time, use Aidl directly
Extending binder Classes
Service Code:
Public classLocalServiceextendsService {//Binder given to clients Private FinalIBinder Mbinder =NewLocalbinder (); //Random Number Generator Private FinalRandom Mgenerator =NewRandom (); /*** Class used for the client Binder. Because We know this service always * runs in the same process as it clients, we don ' t need to deal with IPC. */ Public classLocalbinderextendsBinder {LocalService getService () {//Return This instance of LocalService so clients can call public methods returnLocalService. This; }} @Override Publicibinder onbind (Intent Intent) {returnMbinder; } /**Method for clients*/ Public intGetRandomNumber () {returnMgenerator.nextint (100); }}
Client code:
Public classBindingactivityextendsActivity {LocalService mservice; BooleanMbound =false; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.main); } @Overrideprotected voidOnStart () {Super. OnStart (); //Bind to LocalServiceIntent Intent =NewIntent ( This, LocalService.class); Bindservice (Intent, mconnection, context.bind_auto_create); } @Overrideprotected voidOnStop () {Super. OnStop (); //Unbind from the service if(mbound) {unbindservice (mconnection); Mbound=false; } } /**called when a button was clicked (the button in the "layout" file attaches to * This method with the Android:onclic K attribute)*/ Public voidOnButtonClick (View v) {if(mbound) {//Call a method from the LocalService. //However, if this call were something the might hang and then this request should//occur in a separate thread to avoid slowing down the activity performance. intnum =Mservice.getrandomnumber (); Toast.maketext ( This, "Number:" +num, Toast.length_short). Show (); } } /**defines callbacks for service binding, passed to Bindservice ()*/ PrivateServiceconnection mconnection =Newserviceconnection () {@Override Public voidonserviceconnected (componentname className, IBinder service) {//We ' ve bound to LocalService, cast the IBinder and get LocalService instanceLocalbinder Binder =(localbinder) service; Mservice=Binder.getservice (); Mbound=true; } @Override Public voidonservicedisconnected (componentname arg0) {Mbound=false; } };}Using Messenger
Service Code:
Public classMessengerserviceextendsService {/**Command to the service to display a message*/ Static Final intMsg_say_hello = 1; /*** Handler of incoming messages from clients. */ classIncominghandlerextendsHandler {@Override Public voidhandlemessage (Message msg) {Switch(msg.what) { CaseMSG_SAY_HELLO:Toast.makeText (Getapplicationcontext (),"Hello!", Toast.length_short). Show (); Break; default: Super. Handlemessage (msg); } } } /*** Target We publish for clients to send messages to Incominghandler. */ FinalMessenger Mmessenger =NewMessenger (NewIncominghandler ()); /*** When binding to the service, we return a interface to our Messenger * for sending messages to the service. */@Override Publicibinder onbind (Intent Intent) {Toast.maketext (Getapplicationcontext (),"Binding", Toast.length_short). Show (); returnMmessenger.getbinder (); }}
Client code:
Public classActivitymessengerextendsActivity {/**Messenger for communicating with the service.*/Messenger Mservice=NULL; /**Flag indicating whether we have a called bind on the service.*/ BooleanMbound; /*** Class for interacting with the main interface of the service. */ PrivateServiceconnection mconnection =Newserviceconnection () { Public voidonserviceconnected (componentname className, IBinder service) {//This was called when the connection with the service had been//established, giving us the object we can use to//interact with the service. We is communicating with the//Service using a Messenger, so here we get a client-side//Representation of that from the raw IBinder object.Mservice =NewMessenger (service); Mbound=true; } Public voidonservicedisconnected (componentname className) {//This was called when the connection with the service had been//unexpectedly disconnected--that's, its process crashed.Mservice =NULL; Mbound=false; } }; Public voidSayHello (View v) {if(!mbound)return; //Create and send a message to the service with using a supported ' what ' valueMessage msg = Message.obtain (NULL, Messengerservice.msg_say_hello, 0, 0); Try{mservice.send (msg); } Catch(RemoteException e) {e.printstacktrace (); }} @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.main); } @Overrideprotected voidOnStart () {Super. OnStart (); //Bind to the serviceBindservice (NewIntent ( This, Messengerservice.class), mconnection, context.bind_auto_create); } @Overrideprotected voidOnStop () {Super. OnStop (); //Unbind from the service if(mbound) {unbindservice (mconnection); Mbound=false; } }}Binding Service
Only activities, services, content providers can bind to the service, broadcast receiver can not bind!
Life cycle