One, the binder framework explains
Binder is a framework that provides a server-side interface, Binder driver, client interface three modules
The service side of a binder is actually a Binder class object, the object that once created, the inside will create a hidden thread, the thread will receive the binder driver sent the message, after receiving the message, will execute the binder in the Ontransact () function, and executes different service codes according to the parameters of the function, so first a ontransact () method
Binder Drive
Binder driver, any service-side binder when the object is created, a Mremote object is created in the binder drive, and the type of the object is also the Binder class. When the client accesses the remote service, it passes through the Mremote object.
Program Client
The client wants to access the remote service, it must obtain the corresponding Mremote reference of the service in the Binder object, and as to how to obtain the Mremote object, it can call its Transact () method, and in Binder driver, The Mremote object also overloads the Transact () method
The overloaded content mainly includes:
-Send the parameters passed by the client to the server in the mode of message communication between threads
-When the current thread is suspended, the current thread is the client thread and waits for the service terminal to finish executing the specified function notification (notify).
-Receive notification of the notification thread, then continue sending the client thread and return to the client code area
Note: The client does not directly invoke the binder for the remote service, but in fact it is brokered through the binder driver. There are two binder objects, one is the binder object on the service side, and the other is the binder object in the binder driver. The difference is that the object in the binder driver does not produce a single thread.
Second, the service side of program design
Design the service side generally Android has been implemented for you, but the strength of Android programmers can follow their own implementation of a service, as long as the binder class based on a new service class can be, The following Baseservice code inherits the binder class and implements the service class through the start (String filepath) and stop () methods
public class BaseService extends Binder{ @Override protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException { // TODO Auto-generated method stub return super.onTransact(code, data, reply, flags); } public void start(String filepath) { } public void stop() { }}
To start by creating an instance of Baseservice
You can see a binder_3 thread in the DDMS threads, after defining the service class, you need to rewrite the Ontransact () method, and read the parameters passed by the client in the data variable, the start () method requires the variable filepath variable, The client needs to have a contract with both of the service providers.
When the client puts the first data in the incoming parcel data is the filepath variable, the code for Ontransact () needs to be designed like this:
@Override protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException { switch (code) { case 1000: data.enforceInterface("BaseService"); String filepath=data.readString(); start(filepath); break; default: break; } return super.onTransact(code, data, reply, flags); }
Implementation of the Ontransact () method in Aidl
@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_getMyService:{data.enforceInterface(DESCRIPTOR);this.getMyService();reply.writeNoException();return true;}}
code变量是用于标识客户端期望的调用的哪个函数,因此,双方需要有一个约定的int值用来识别服务器,不同的服务器有不同的code值,该值和客户端的transact()函数中的第一个code值是一致的,enforceInterface()是为了校验,它与客户端的writeInterfaceToken()对应readString()用于从包裹去除一个字符串,去除filePath变量后,就可以调用服务端的start()函数了如果IPC调用的客户端期望返回一些结果,则可以在返回包裹reply中调用parcel提供的相关函数写入相应结果.
Third, binder client design
In order to use the service provided by the server, the client must go back to the service side in the binder driver corresponding to the Mremote variable reference, get the variable to drink and then use the variable transact () method.
The Transact () method body in the IBinder class is as follows
public boolean transact(int code, Parcel data, Parcel reply, int flags) throws RemoteException;
Where data represents the package to be passed to the Remote Binder Service (Parcel), the parameters required for the remote service letter must be placed in the package, and the package can only be placed into certain types of variables, including commonly used atomic types such as String,int,long, To see all the types of packages that can be placed, you can refer to the parcel class, in addition to the general atomic variables, parcel also provides a writeparcel () method that can contain a small package in the package, so when you invoke the Binder remote service, The parameters of a service function are either an atomic class or must inherit from the parcel class, otherwise it cannot be passed.
The client of the service needs to implement the IBinder interface, and Android has implemented the IBinder abstract method through the binder class, where the client needs to call the Transact () method.
protected Boolean ontransact (int code, PARCEL data, Parcel reply, int flags) throws RemoteException {I F (Code = = interface_transaction) {reply.writestring (Getinterfacedescriptor ()); return true; } else if (code = = dump_transaction) {parcelfiledescriptor fd = Data.readfiledescriptor (); string[] args = Data.readstringarray (); if (FD! = null) {try {dump (fd.getfiledescriptor (), args); } finally {try {fd.close (); } catch (IOException e) {//swallowed, not propagated back to the caller} }}//Write the Strictmode header. if (reply! = null) {reply.writenoexception (); } else {strictmode.cleargatheredviolations (); } return true; }return false; } public Final Boolean transact (int code, PARCEL data, Parcel reply, int flags) throws RemoteException { if (false) log.v ("Binder", "Transact:" + code + "to" + this); if (data! = null) {data.setdataposition (0); } boolean r = Ontransact (code, data, reply, flags); if (reply! = null) {reply.setdataposition (0); } return R; }
以上代码分析,首先,包裹不是客户端自己创建的,而是调用了Parcel.obtain()申请的,就像邮局一样,用户一般只能用邮局提供的信封,其中data和reply变量由客户端提供,reply变量用户服务端把返回的结果放入其中.
public class MyParcel implements Parcelable{@Overridepublic int describeContents() { // return 0;}/* * 用于标注远程服务名称,理论上这个是不需要的 ,因为客户端已经 * @see android.os.Parcelable#writeToParcel(android.os.Parcel, int) */@Overridepublic void writeToParcel(Parcel dest, int flags) {}}
The Writeinterfacetoken () method labels the remote service name, which in theory is not required because the client has already obtained a binder reference for the specified remote service and does not invoke other remote services. This name is used as binder driver to ensure that the client's missing items are invoked on the specified service side
The WriteString () method is used to add a string variable to the package. Note that the content added in the package is ordered, which must be agreed by the client and the server in advance, and the variables are taken in the order of the Ontransact () method in the server.
Call the Transact () method, after calling the method, the client thread enters the binder driver, the binder driver starts the hidden thread and sends a message to the remote service that contains the package that the client sent in, and after the service has taken the parcel, it splits the package. Then executes the specified service function, executes the execution, and then puts the execution result into the reply package provided by the client, and then the server sends a notify message to the binder driver, allowing the client thread to return from the Binder drive code area to the client code area
The meaning of the last parameter of Transact () is that the mode of executing the IPC call is divided into two types: one is bidirectional, and the constant 0 means that the service end will return certain data after executing the specified service, one is unidirectional, and is represented by constant 1, meaning that no data is returned.
Finally, the client can parse the returned data from the reply, as well as the data contained in the package must be ordered, and the order must be the service side and the client's prior agreement.
Four, using the service class
Three designs to two questions:
- How the client obtains a reference to binder
- Both the client and the server must agree on two things in advance.
The order of the parameters of the service-side function in the package
int type identification of different functions on the service side
Gets the Binder object
The Android system provides the StartService () method for starting the client, and for the client, the following two methods can be used to link the service, which is prototyped in the Android.app.ContextImpl class,
//这个方法是用于启动客户端服务 @Override public ComponentName startService(Intent service) { return super.startService(service); } ServiceConnection connection=new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { // TODO Auto-generated method stub } //该方法是用于绑定服务 @Override public void onServiceConnected(ComponentName name, IBinder service) { // TODO Auto-generated method stub } };
Use the Aidl tool to guarantee the order of the parameters within the package
Android provides the Aidl tool that can convert a aidl file into a Java file, in which the Java class file, while overloading Transact () and Ontransact (), unifies the package and reads the package parameters, This allows the designer to focus on the service code itself.
Aidl tool is not necessary, for Daniel, can manually write a parameter uniform package deposit and parcel readout code is a small case (PS: Bo Master level can barely write 23333)
//aidl代码package com.example.androidneihe;interface MyAidl{ void getMyService();}
aidl文件语法基于java,package指定的是输出后的java文件对应的包名,如果该文件需要引用其他类对应服务的类名,则需要时使用import关键字,但需要注意的是包裹内只能写入以下三个类型的内容:
- Java atomic types, such as int,long,string variables;
- Binder Reference.
- Implements the object of the Parcelale
- So, basically. The type referenced by import can only be the above three types
The interface keyword, which sometimes adds a oneway to the front of the interface, means that the method provided by the service is not a return value, that is, the void type.
Package Com.example.androidneihe;public Interface Myaidl extends android.os.iinterface{/** local-side IPC Implementation stub class. */public static abstract class Stub extends Android.os.Binder implements com.example.androidneihe.myaidl{private static Final java.lang.String descriptor = "Com.example.androidneihe.MyAidl";/** Construct the stub at attach it to the interface . */public Stub () {this.attachinterface (this, descriptor);} /** * Cast an IBinder object to an Com.example.androidneihe.MyAidl interface, * Generating a proxy if needed. */public static Com.example.androidneihe.MyAidl asinterface (Android.os.IBinder obj) {if ((Obj==null)) {return null;} Android.os.IInterface iin = obj.querylocalinterface (descriptor); if ((Iin!=null) && (iin instanceof Com.example.androidneihe.MyAidl)) {return ((com.example.androidneihe.MyAidl) iin);} return new Com.example.androidneihe.MyAidl.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_getmyservice:{data.enforceinterface (descriptor); This.getmyservice (); Reply.writenoexception (); return true;}} Return Super.ontransact (Code, data, reply, flags);} private static class Proxy implements Com.example.androidneihe.myaidl{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 Getmyservice () 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_getmyservice, _data, _reply, 0); _reply.readexception ();} finally {_reply.recycle (); _DATA.REcycle ();}}} static final int transaction_getmyservice = (Android.os.IBinder.FIRST_CALL_TRANSACTION + 0);} public void Getmyservice () throws android.os.RemoteException;}
The code mainly accomplishes the following three tasks.
- A Java interface that internally contains the service functions declared by the Aidl file, the name of the class is Myaidl, and the class is based on the IInterface interface, which is required to provide a asbinder () function.
- Defines a proxy class that will be used as a client program to access the proxy on the server. The so-called proxy is mainly for the second problem mentioned above-the order of the write parameters within the uniform package.
- Defines a stub class, which is an abstract class, based on the binder class, and implements the Myaidl interface, which is primarily used by the server. The reason why this class is defining the class abstract is that the specific service function must be implemented by the programmer, so There can be no specific implementation in the stub class defined in the Myaidl interface. In addition, in the stub class, the Ontransact () method is overloaded, and the natural path of the Aidl tool should be the order in which the corresponding parameters are removed from the package.
Some int constants are defined in the stub class, such as Transaction_start, which correspond to the service function, the value of the first parameter of the Transact () and Ontransact () methods code
In the stub class, in addition to the tasks described above, the stub also provides a Asinterface () function. This function is provided for the purpose of:
The first thing to be clear is that the code generated by the love trouble can be manually written by the application programmer, the function in Myaidl is only one encoding habit, asinterface that is, the reason for providing this function is that the service provides services in addition to other processes can be used outside, The service can also be used by other classes within the service process, which is obviously not required to be called by the IPC, but can be called directly inside the process, and the binder object is a local binder reference.
When a binder object is created, a binder object is created inside the server process, and a binder object is created in the binder drive, and if the binder is fetched from the remote server, the Binder object in the binder driver is returned. If you get binder objects from within a server-side process, you get binder objects from the service side itself, and the flowchart is visible
The Asinterface () function uses the Querylocalinterface () method to provide a unified interface, whether the client or the local side, when the binder object is obtained, the object can be retrieved as a asinterface () Parameter returns an Myaidl interface that either uses the proxy class or uses the response function implemented by the stub.
The binder of Android kernel