Android bind service learning notes

Source: Internet
Author: User
Tags mremote

Bind service can bind application components to local services, or bind services of other applications. In Android, each application runs on

In your own virtual machine, each virtual machine corresponds to a process in the Linux kernel. Therefore, you can bind the service of other applications to implement inter-process communication.

Binder is a base class for objects that can be remotely operated. It is a lightweight Remote Process calling mechanism and the core part is defined in the ibinder class.

This class is the implementation of an ibinder class, which provides standard support for creating a local implementation object. The subsequent binding is implemented based on the binder.

It is relatively simple to bind a local service and interact with it. Create a binder instance in the service. This instance requires a public method for the biner.

Call, return the service instance in this public method, so that you can call the public method in the service. Binder instance callback through onbind

The method is returned to the biner:

 

public class LocalService extends Service {    private final IBinder mBinder = new LocalBinder();    private final int mserviceparam=10; public class LocalBinder extends Binder {        LocalService getService() {            // Return this instance of LocalService so clients can call public methods            return LocalService.this;        }    }    @Override    public IBinder onBind(Intent intent) {        return mBinder;    }    /** method for clients */    public int getServiceParem(){      return mserviceparam;        }}

Bind a service by using the following methods:

 

 

bindService (Intent service, ServiceConnection conn, int flags)

There are two callback methods in the serviceconnection class. when the service is successfully bound, the two methods are called after the binding is canceled:

 

 

private ServiceConnection mConnection=new ServiceConnection (){@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {// TODO Auto-generated method stub}@Overridepublic void onServiceDisconnected(ComponentName name) {// TODO Auto-generated method stub}};

Bind and interact with services of different applications. Other classes are required. There are two methods: Messenger and aidl.

 

1. Messenger, a Chinese translation of "Messenger", is responsible for sending information, which can be performed across processes,

Messenger has two constructors:

A. Public Messenger (handler target)

Handler is used to process the message sent by messenger,

That is, a messenger will have a handler corresponding to it,

Get a binder object through Messenger. getbinder () and return it to the client in the onbind () method of the service.

 

public class MyService extends Service{ static final int MSG_SEND_FROM_REMOTE=1; static final int MSG_SEND_FROM_LOCAL=2; static final int MSG_RELY_FROM_SERVICE=3; class IncomingHandler extends Handler{  public void handleMessage(Message msg){ switch(msg.what){ case MSG_SEND_FROM_REMOTE: Toast.makeText(getApplicationContext(),"hello,i am from remote,send content is"+msg.getData().getString("sendContent"), Toast.LENGTH_LONG).show(); try {msg.replyTo.send(Message.obtain(null, MSG_RELY_FROM_SERVICE, null));} catch (RemoteException e) {// TODO Auto-generated catch blocke.printStackTrace();} break; case MSG_SEND_FROM_LOCAL: Log.d("remoteservice", "MSG_SEND_FROM_LOCAL"); Toast.makeText(getApplicationContext(),"hello,i am from local", Toast.LENGTH_LONG).show(); break;     default: super.handleMessage(msg); } }  } final Messenger mMessenger=new Messenger(new IncomingHandler());@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn mMessenger.getBinder();}}

 

 

B. Public Messenger (ibinder target)

This constructor is generally used to bind a service component. The passed binder object is returned from the service, so that the messenger will

Send a message using this messenger, which can be received in the service and processed accordingly.

At this point, we can only send messages from the binding component to the service. The service cannot send messages to the binding component,

To implement bidirectional communication, create another messenger object in the binding component and use the public Messenger (handler target) construction method,

Assign this messenger to MSG. replyto and send it to the service. The service uses this messenger to send a message to the binding component.

 

Private serviceconnection mconnection = new serviceconnection () {@ overridepublic void onserviceconnected (componentname name, ibinder Service) {// todo auto-generated method stubmmessenger = new messenger (service ); // use the binder returned by the service to build the instance send. setenabled (true) ;}@ overridepublic void onservicedisconnected (componentname name) {// todo auto-generated method stubmmessenger = NULL; send. setenabled (false );}};
Class incominghandler extends handler {// construct the handler bound to the component. The message sent by the service processes public void handlemessage (Message MSG) {Switch (MSG. what) {Case msg_rely_from_service: sendcontent. settext ("Service received"); break; default: Super. handlemessage (MSG );}}}
Private messenger remessenger = new messenger (New incominghandler (); // build the messenger that binds the component

 

Private void sendmessage () throws RemoteException {// send message MSG = message. obtain (null, msg_send_from_remote, null); bundle DATA = new bundle (); data. putstring ("sendcontent", sendcontent. gettext (). tostring (); MSG. setdata (data); MSG. replyto = remessenger; mmessenger. send (MSG); log. D ("remoteservice", "sendmessage ");}

2. aidl Android Interface Definition Language,

 

Create an interface definition file with. aidl as the Suffix in the src/directory. The Android SDK automatically creates a Java file with the same name in the GEN/directory,

A Java file is an ibinder interface file.

For example, the. aidl file is defined:

 

package txj.remoteservice;interface IRemoteService {      void showResult();}

A. Java file is automatically generated:

 

 

/* * This file is auto-generated.  DO NOT MODIFY. * Original file: E:\\android\\newworkspase\\RemoteService\\src\\txj\\remoteservice\\IRemoteService.aidl */package txj.remoteservice;public interface IRemoteService extends android.os.IInterface{/** Local-side IPC implementation stub class. */public static abstract class Stub extends android.os.Binder implements txj.remoteservice.IRemoteService{private static final java.lang.String DESCRIPTOR = "txj.remoteservice.IRemoteService";/** Construct the stub at attach it to the interface. */public Stub(){this.attachInterface(this, DESCRIPTOR);}/** * Cast an IBinder object into an txj.remoteservice.IRemoteService interface, * generating a proxy if needed. */public static txj.remoteservice.IRemoteService asInterface(android.os.IBinder obj){if ((obj==null)) {return null;}android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);if (((iin!=null)&&(iin instanceof txj.remoteservice.IRemoteService))) {return ((txj.remoteservice.IRemoteService)iin);}return new txj.remoteservice.IRemoteService.Stub.Proxy(obj);}@Override public android.os.IBinder asBinder(){return this;}@Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException{switch (code){case INTERFACE_TRANSACTION:{reply.writeString(DESCRIPTOR);return true;}case TRANSACTION_showResult:{data.enforceInterface(DESCRIPTOR);this.showResult();reply.writeNoException();return true;}}return super.onTransact(code, data, reply, flags);}private static class Proxy implements txj.remoteservice.IRemoteService{private android.os.IBinder mRemote;Proxy(android.os.IBinder remote){mRemote = remote;}@Override public android.os.IBinder asBinder(){return mRemote;}public java.lang.String getInterfaceDescriptor(){return DESCRIPTOR;}@Override public void showResult() throws android.os.RemoteException{android.os.Parcel _data = android.os.Parcel.obtain();android.os.Parcel _reply = android.os.Parcel.obtain();try {_data.writeInterfaceToken(DESCRIPTOR);mRemote.transact(Stub.TRANSACTION_showResult, _data, _reply, 0);_reply.readException();}finally {_reply.recycle();_data.recycle();}}}static final int TRANSACTION_showResult = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);}public void showResult() throws android.os.RemoteException;}

The stub abstract internal class inherits the binder and implements its own defined interface.
Create an extends stub class in the service and implement the interface method defined by yourself. Return an object of this class in the onbind () method.

 

 

public class AidlService extends Service {     private IRemoteService.Stub mbindder=new IRemoteService.Stub() {@Overridepublic void showResult(){// TODO Auto-generated method stub//Toast.makeText(AidlService.this, "the toast show from AidlService", Toast.LENGTH_LONG).show();Log.d("remoteservice","showResult");}};@Overridepublic IBinder onBind(Intent intent) {// TODO: Return the communication channel to the service.return mbindder;} public void onDestroy(){ Log.d("remoteservice","onDestroy");  super.onDestroy(); }}    

Copy the. aidl file to the src/file directory of the application to which the service is bound (the package name must be the same). The corresponding Java file is automatically generated in GEN.

 

After the binding component is successfully bound, the binder returned by the service is obtained. You can use the following method to obtain the object of the interface type you have defined. You can call the method implemented in the service:
Maidlservice = iremoteservice. stub. asinterface (service );

Implementation Code:

 

private ServiceConnection mAidlConnection=new ServiceConnection(){@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {// TODO Auto-generated method stubmAidlService=IRemoteService.Stub.asInterface(service);Log.d("ConMainActivity", "onServiceConnected");try {mAidlService.showResult();} catch (RemoteException e) {// TODO Auto-generated catch blocke.printStackTrace();}}@Overridepublic void onServiceDisconnected(ComponentName name) {// TODO Auto-generated method stub}};

Source code: available later

 

 

Related Article

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.