Thoroughly understand Aidl and its use in Android

Source: Internet
Author: User

1, why should there be aidl?No matter what you learn, the first thing you have to figure out is why you should have this, not to say that it is reasonable, that there is a certainty, but you still don't understand. For Aidl Some people's simple concept is that aidl can access other applications across processes, and other applications to communicate, I tell you, many technologies can be accessed, such as broadcast (app a broadcasts a specified action in androidmanifest.xml) application B sends a broadcast of the specified action, a can receive information, which can also be seen as communication between different applications (but this communication is unidirectional), and, as ContentProvider, by URI Access to other applications, but this is not a communication between applications. Perhaps the most confusing thing is that Android comes with Messager, which is the communication between applications. So why should there be aidl, Official document introduction Aidl in this sentence:
Note:using Aidl is necessary only if you allow clients from different applications to access your service for IPC and WAN T to handle multithreading in your service. If you don't need to perform concurrent IPC across different applications, you should create your interface by Implementi ng a Binder or, if you want to perform IPC, but does not need to handle multithreading, implement your interface using a Mes Senger. Regardless, be sure this understand Bound Services before implementing an aidl.
The first sentence is the most important, "You only have to use Aidl when you allow access to your services from different clients and you need to deal with multithreading issues", in other cases you can choose other methods, such as using messager to communicate across processes. Visible Aidl is for multi-threaded, multiple-client concurrent access. Messager is a single-threaded process. Or the official document is clear, a word can understand why to have aidl. So write a aidl and try it.2, Aidl useFirst, define the Aidl file
Iremoteservice.aidlpackage com.example.android;//Declare Any non-default types here with import statements/** example  Service Interface */interface Iremoteservice {    /** Request the process ID of the This service, to does evil things with it. *    /int getpid ();    /** demonstrates some basic types that's can use as parameters     * and return values in Aidl.     *    /void basictypes (int anint, long along, Boolean aboolean, float afloat,            double adouble, String astring);}
This code is also an official document. Named Iremoteservice.aidl, placed under the Com.example.android package (this can be arbitrary), after saving the Android compiler will automatically generate Iremoteservice.java files in the Gen directorySecond, define our service, Ddservice.java, and need to register in Androidmanifest.xml, and add "duanqing.test.aidl" Action
Package Com.example.service;import Com.example.android.iremoteservice;import Android.app.service;import Android.content.intent;import Android.os.ibinder;import Android.os.process;public class DDService extends Service {@ overridepublic void OnCreate () {super.oncreate (); System.out.println ("Ddservice onCreate ..." + "Thread:" + thread.currentthread (). GetName ());} @Overridepublic ibinder onbind (Intent arg0) {System.out.println ("Ddservice onbind"); return mbinder;} Private final Iremoteservice.stub Mbinder = new Iremoteservice.stub () {public int getpid () {System.out.println ("Thr    EAD: "+ thread.currentthread (). GetName ());        System.out.println ("Ddservice getpid");    return Process.mypid (); } public void Basictypes (int anint, long along, Boolean aboolean, float afloat, double adouble, String astring)    {System.out.println ("Thread:" + thread.currentthread (). GetName ()); System.out.println ("Basictypes adouble:" + adouble + "Anint:" + anint+ "Aboolean" + Aboolean+ "astring" + astring); }};}

So our service end is finished, the server run to the simulator (or mobile phone), wait a while to see the printing information, focusing on "thread name"
third, implement the client test code Create another project, also need to add Aidl protocol file (this is a standard protocol file, define the external service), here I listed my test code:
Package Com.example.aidlclient;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;import Android.os.process;import Android.os.remoteexception;import Android.view.view;import Com.example.android.iremoteservice;public class Mainactivity extends Activity {private    Iremoteservice Remoteservice;        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);    Setcontentview (R.layout.activity_main); } serviceconnection conn = new Serviceconnection () {@Overridepublic void onservicedisconnected (componentname name) {} @Overridepublic void onserviceconnected (componentname name, IBinder service) {Remoteservice = IRemoteService.Stub.asInterface (service); try {int pid = remoteservice.getpid (); int currentpid = Process.mypid (); System.out.println ("Currentpid:" + Currentpid + "remOtepid: "+ pid"); Remoteservice.basictypes (1223, True, 12.2f, 12.3, "Our love, I understand");} catch (RemoteException e) {e.printstacktrace ();}    System.out.println ("Bind success!" + remoteservice.tostring ());}; /** * Monitor button click * @param view */public void ButtonClick (view view) {System.out.println ("Begin Bindservice    ");    Intent Intent = new Intent ("Duanqing.test.aidl");    Bindservice (Intent, Conn, context.bind_auto_create);    } @Override protected void OnDestroy () {Super.ondestroy ();    Unbindservice (conn); }}
4. ImplementationClick the client button, execute, and look at the print information:
look at the server print, Ddservice onCreate ... Thread:main, the main thread, when the client invokes the server-side Getpid method, the server is executed in Thread:binder2, and when the client invokes the server-side Basictype method, the server is executed in Thread:binder1

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.