use of Aidl:
The most common use of aidl is the cross-process communication of service, so we write a cross-process communication between activity and service.
First, we create a new Aidl file in as (PS: Now Aidl does not require the same as the Java package name):
package aidl;interface IMyInterface { String getInfor(String s);}
As you can see, here we have a method getinfor (string s), takes a string argument, and then returns a string, well, quite simple.
Then you can find the Java file generated by the Aidl file in the app/generated/source/aidl/debug/aidl with your sync project. You may also be intimidated by the seemingly ' bulky ' class, and now we're not going to let it go.
Then just look at the service:
Public class myservice extends Service { Public Final StaticString TAG ="MyService";PrivateIBinder Binder =NewImyinterface.stub () {@Override PublicStringgetinfor(String s)throwsremoteexception {log.i (TAG, s);return "I am the string returned by the Service"; } };@Overrid Public void onCreate() {Super. OnCreate (); LOG.I (TAG,"Oncreat"); }@Override PublicIBinderOnbind(Intent Intent) {returnBinder }}
Here we write a service, it is relatively simple to look at. A new Imyinterface.stub () is first transformed into a ibinder and then returned back in the Onbind method. You may have noticed that in imyinterface.stub () we rewrote the Getinfor (String s) method, which is the interface defined in our Aidl file.
Yes, because we want to see cross-process communication, so we define MyService as a new startup process:
<service android:name=".server.MyService" android:process="com.xu.remote" />
defined as startup in a new process, you only need to declare it in androidmainfest.xml with a process attribute, but there are two places worth noting:
1. The default process name of the component is the package name;
2. When defining a new process name, it needs to be in the form of a package (EG:COM.XU.AIDL).
Next, we continue to look down:
Public class mainactivity extends appcompatactivity { Public Final StaticString TAG ="Mainactivity";PrivateIMyInterface MyInterface;PrivateServiceconnection serviceconnection =NewServiceconnection () {@Override Public void onserviceconnected(componentname name, IBinder service) {MyInterface = IMyInterface.Stub.asInterface (service); LOG.I (TAG,"Connection Service Success");Try{String s = myinterface.getinfor ("I'm a string from the activity."); LOG.I (TAG,"The string received from the service:", T); }Catch(RemoteException e) {E.printstacktrace (); } }@Override Public void onservicedisconnected(componentname name) {LOG.E (TAG,"Connection Service failed"); } };@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); Startandbindservice (); }Private void Startandbindservice() {Intent service =NewIntent (mainactivity. This, Myservice.class);//startservice (service);Bindservice (service, serviceconnection, context.bind_auto_create); }}
Because it is primarily a communication between service and activity, there is no UI to keep the code neat.
In OnCreate (Bundle savedinstancestate), we call a method of our own definition startandbindservice (), in which we generate a intent, and then Bindservice The intent three parameters were intent, serviceconnection, and Flag.
Intent we don't have to say, let's look at the next two parameters:
In the activity, we new a serviceconnection and realized his two methods onserviceconnected, onservicedisconnected. In onserviceconnected we converted the IBinder to our defined imyinterface through the IMyInterface.Stub.asInterface (service). We then called the Getinfor method, passed a string and fetched a string from MyService, and printed the log.
For the context.bind_auto_create we preach, it means that if the service is not created, it is created when the service is bound. Of course, there are a lot of flags here, and I don't say it all.
Then, our code is done, start running the test!
Looking at the results of the operation, we get the results we want in these two different processes, so a cross-process communication implemented with AIDL is done. Of course our demo (not misspelled this time), getinfor without any logic, you can also add some logic to perform some complex operations.
Aidl's understanding:
Now that we're going to use the aidl, we're not going to uncover the mystery.
IBinder in the service
Remember that we used the new imyinterface.stub () up in MyService to IBinder and then return in the Onbind method. Then let's look at Imyinterface.stub:
publicstaticabstractclass Stub extends android.os.Binder implements aidl.IMyInterface {..........}
As you can see, the stub is a static abstract class in IMyInterface, inherits the binder, and implements the IMyInterface interface. This explains why we need to implement imyinterface in the definition of imyinterface.stub, and also explains why we can transform imyinterface.stub upward into ibinder.
The IMyInterface in activity
In activity, through Serviceconnection connection MyService and successful callback onserviceconnected we send back IBinder through IMyInterface.Stub.asInterface (service) conversion to IMyInterface, let's see how this can be converted:
Public Static Abstract class Stub extends android. os. Binder Implements aidl. IMyInterface {.......... Public StaticAidl. IMyInterfaceAsinterface(Android.os.IBinder obj) {if(obj = =NULL)) {return NULL; }//Check binder is not in the current processAndroid.os.IInterface iin = obj.querylocalinterface (descriptor);if(((Iin! =NULL) && (iininstanceofAidl. IMyInterface)) {return(Aidl. IMyInterface) iin); }return NewAidl. IMyInterface.Stub.Proxy (obj);}}
First, what we should understand is that the IBinder returned is the IBinder we return in the service's Onbind () method, and then we call the static method in the stub asinterface and pass in the IBinder when the argument is returned.
In the Asinterface method, it is first judged whether the incoming IBinder is NULL, if NULL returns a null, and then the IBinder is not in the current process, if so, then return directly to IMyInterface, If not, return to IMyInterface.Stub.Proxy (obj). Here I think it is necessary to understand that the direct return of the imyinterface is the implementation of the defined interface method getinfor. Because of what is implemented in Imyinterface.stub. Of course, if it is in the same process, then we call the method of IMyInterface in the local call method, directly call on it.
If it is not in the same process, it will return IMyInterface.Stub.Proxy (obj):
Private Static class Proxy implements aidl. IMyInterface { PrivateAndroid.os.IBinder Mremote; Proxy (Android.os.IBinder remote) {mremote = remote; }@Override PublicAndroid.os.IBinderAsbinder() {returnMremote; } PublicJava.lang.StringGetinterfacedescriptor() {returnDescriptor; }@Override PublicJava.lang.Stringgetinfor(java.lang.String s)throwsandroid.os.RemoteException {Android.os.Parcel _data = Android.os.Parcel.obtain (); Android.os.Parcel _reply = Android.os.Parcel.obtain (); Java.lang.String _result;Try{_data.writeinterfacetoken (descriptor); _data.writestring (s);//Transfer data to a remoteMremote.transact (Stub.transaction_getinfor, _data, _reply,0); _reply.readexception ();//Accept data returned from the remote_result = _reply.readstring (); }finally{_reply.recycle (); _data.recycle (); }return_result; } }Static Final intTransaction_getinfor = (Android.os.IBinder.FIRST_CALL_TRANSACTION +0);}
In the proxy, we first successfully return the service connection ibinder its internal variable mremote, here to mention, here IBinder or MyService Onbind returned. Then, when we call the IMyInterface method, is actually called the Proxy method, which is why this class is called Porxy reason.
When calling Imyinterface.getinfor (String s), we look at the getinfor in the proxy, first obtained two parcel objects _data, _data, from the variable name can be seen, one is to transmit data, The other is to accept the return data. Next, write the descriptor (that is, the full name of the class) to the _data, and then write the method parameters. And then there's the most important step,
Mremote.transact (Stub.transaction_getinfor, _data, _reply, 0);
Here we call the IBinder Transact method to pass the data to the remote server. Then in our remote MyService, the stub in the inside Will callback Ontransact () (because you send the data to a remote service, the remote service receives the data will be callback)
Note: This is called in the remote service.
@Overridepublic BooleanOntransact (intCode, Android.os.Parcel data, android.os.Parcel reply,intFlagsthrowsandroid.os.RemoteException {Switch(code) { CaseInterface_transaction: {reply.writestring (descriptor);return true; } CaseTransaction_getinfor: {data.enforceinterface (descriptor); Java.lang.String _arg0;//Remove Parameters_arg0 = Data.readstring ();//Remote service calls its own locally implemented method to get the return valueJava.lang.String _result = This. Getinfor (_ARG0); Reply.writenoexception ();//write return valueReply.writestring (_result);return true; } }return Super. Ontransact (Code, data, reply, flags);}
The Ontransact method is implemented inside the stub.
Let's take a look at its four parameters:
code: Each method has a number of type int to differentiate (swicth in the back), in our case the stub.transaction_getinfor in our proxy.
Data : This is a pass-through that contains our parameters, as well as the description of the class.
Reply: Returns the data that we want to write whether the exception has occurred, and the return value
Flags: Whether the method has a return value and 0 indicates a return value.
Call ontransact means that there is data coming, first of all through SWICTH to determine which method, and then take out the method parameters, call the local implementation of the method to get the return value, write the return value to reply. Finally, returns true to send the data out, playing false will not return the results to the activity. This means that only return true, we can accept the data returned from the remote.
//传送数据到远程的 mRemote.transact(Stub.TRANSACTION0); _reply.readException(); //接受从远端传回的数据 _result = _reply.readString();
Note: The service also sends the data out for the client to accept.
The service sends out the data, and the client receives it, and it goes back one layer at a level. So, when we simply call IMyInterface getinfor, first proxy transact send out the data, and then the service side of the Ontransact to accept and process the transmitted data, and then write the processed data to the return value and send to the client, After the client reads the value, it is returned as the return value of the calling method.
Then aidl the basic principle is this, see understand aidl, only to find the original aidl but is to help us generate those data write, transmit, read the method just. So, we write a Do not aidl cross-process communication is also very simple, quick hands-on try it!
The use and understanding of aidl in Android