Introduction to the Aidl of "ANDROID-IPC"

Source: Internet
Author: User

Resources:

1, "Android Development Art Exploration" chapter II 2.4.4

2. Android aidl Binder Framework parsing: http://blog.csdn.net/lmj623565791/article/details/38461079

3. Do you really understand the in, out, Inoutm in Aidl: http://www.open-open.com/lib/view/open1469494342021.html

4, MU class network "aidl-small white growth in mind"

1, Aidl Introduction

Android System rules: Each application has a single copy of the virtual machine, one application and another application does not have the means to communicate directly, so as to ensure the security of in-process data, but also ensure that one application crashes will not cause other applications to crash. Two processes if you want to communicate, you can only communicate through the underlying Android system.

Aidl (Android Interface definition Language,android Interface Definition language) is an IPC (inter-process communication, cross-process communication) method in Android, It allows us to write an interface that serves as a bridge for client and server communication. Aidl is an Android-based language specification for client and server-side communication that is defined by the IDL itself.

2. How to use Aidl

In this chapter, we learn the use of aidl through an example.

In this example, there are server and client, the service side has the function of operation book, the client invokes the function of the server.

Because book is not a basic data type, you want book to be passed between multiple processes, and the book needs to be serialized with the following code:

 PackageMy.itgungnir.aidl;ImportAndroid.os.Parcel;Importandroid.os.Parcelable;/*** Book entity class*/ Public classBookImplementsparcelable {PrivateString Booname; Private intPirce;  PublicBook (String Booname,intPirce) {         This. Booname =Booname;  This. Pirce =Pirce; }    protectedBook (Parcel in) {Booname=in.readstring (); Pirce=In.readint (); }     Public Static FinalCreator<book> Creator =NewCreator<book>() {@Override PublicBook Createfromparcel (Parcel in) {return NewBook (in); } @Override PublicBook[] NewArray (intsize) {            return NewBook[size];    }    }; @Override Public intdescribecontents () {return0; } @Override Public voidWritetoparcel (Parcel dest,intflags)        {dest.writestring (booname);    Dest.writeint (Pirce); }}

Our idea is to define the method of manipulating book lists on the server side (Add books, query all books), and then remotely invoke these two methods on the server side of the client to manipulate the books.

The following is an example of writing code and detailed instructions.

2.1. Creation of AIDL interface

Let's start by introducing the definition syntax for the Aidl interface:

1. Data types supported by the Aidl file:

(1) Basic data type (int, long, char, Boolean, double, etc.);

(2) string and charsequence;

(3) List: Only support ArrayList, inside each element must be able to be aidl support;

(4) Map: Only support HashMap, each element inside must be able to be aidl support, including key and value;

(5) Parcelable: All objects that implement the Parcelable interface;

(6) Aidl: All Aidl interfaces themselves can also be used in aidl files.

2. Custom Parcelable objects and Aidl objects must be explicitly import in, regardless of whether they are in the same package as the current Aidl file.

3. If a custom Parcelable object is used in the Aidl file, a aidl file with the same name must be re-built and declared as a parcelable type.

4, Aidl interface method, in addition to the basic types of parameters, other types of parameters must be marked with Data flow: in indicates that the data can only flow from the client to the server, out means that data can only flow from the server to the client; InOut indicates that data flows in two directions between the server and the client. Note: The base data type is default and can only be in the flow direction.

5. Only methods are supported in the Aidl interface, and declaring static constants is not supported.

6, AIDL package structure in the server and the client to be consistent, otherwise the operation will be wrong, because the client needs to deserialize all the classes in the service side and the Aidl interface, if the full path of the class is not the same, the deserialization cannot be completed, the program will not work properly.

Next we create a Aidl interface Ibookmanager.aidl, which uses the book class, so we also need to create a book.aidl file.

The code in the Book.aidl file is as follows:

 Package my.itgungnir.aidl;parcelable Book;

The code in the Ibookmanager.aidl file is as follows:

 Package My.itgungnir.aidl; Import My.itgungnir.aidl.Book; Interface Ibookmanager {    List<Book> getbooklist ();     void Addbook (in Book book);}

As you can see, the syntax in these two aidl files exactly follows the AIDL syntax described above.

2.2, the implementation of the service side

Once we have defined the Aidl interface, we can implement this interface. Create a service class Bookmanagerservice with the following code:

ImportAndroid.app.Service;Importandroid.content.Intent;ImportAndroid.os.Binder;ImportAndroid.os.IBinder;Importandroid.os.RemoteException;Importandroid.support.annotation.Nullable;Importjava.util.ArrayList;Importjava.util.List;ImportMy.itgungnir.aidl.Book;ImportMy.itgungnir.aidl.IBookManager;/*** Define service-side services to implement Aidl interface*/ Public classBookmanagerserviceextendsService {PrivateCopyonwritearraylist<book> Booklist =NewCopyonwritearraylist<>(); PrivateBinder Binder =Newibookmanager.stub () {@Override PublicList<book> getbooklist ()throwsRemoteException {returnBooklist; } @Override Public voidAddbook (book book)throwsremoteexception {booklist.add (book);    }    }; @Override Public voidonCreate () {Super. OnCreate (); Booklist.add (NewBook ("Android", 20)); Booklist.add (NewBook ("IOS", 17)); } @Nullable @Override Publicibinder onbind (Intent Intent) {returnBinder; }}

In this class, we create a stub object that handles the data in the two methods of the object, and finally returns the stub in the Onbind () method.

When writing this class, it is important to note that we do not use ArrayList in this class, but rather a copyonwritearraylist class (this class does not inherit from ArrayList). This copyonwritearraylist support is a list that supports concurrent read/write. Since Aidl is executed in the binder thread pool on the server side, when multiple clients are connected at the same time, there is a situation where multiple threads concurrently access it, so we are going to handle thread synchronization in the Aidl method, and Copyonwritearraylist can automate thread synchronization.

In addition, said before, Aidl only support ArrayList, but Copyonwritearraylist does not inherit from ArrayList, why Aidl still support it? This is because the abstract list is supported in Aidl, and the list is just an interface, so while the server returns the Copyonwritearraylist, In binder, however, the data is accessed according to the list specification and eventually a new ArrayList is passed to the client. Similar to this class is the Concurrenthashmap in the map.

After we have finished writing the service class, we need to register the service in the manifest file with the following code:

<ServiceAndroid:name=". Bookmanagerservice ">    <Intent-filter>        <ActionAndroid:name= "My.itgungnir.aidl.book_server" />        <categoryAndroid:name= "Android.intent.category.DEFAULT" />    </Intent-filter></Service>

At this point, the service-side code is written to completion.

2.3, the implementation of the client

At the client, we first bind the service-side service, convert the binder interface returned by the server to the Aidl interface, and then we can invoke the service-side method.

It is important to note that the Aidl file and the Parcelable class used in the aidl need to have one copy on both the server and the client, and the package path must be the same.

The code in the client's mainactivity is as follows:

ImportAndroid.content.ComponentName;ImportAndroid.content.Context;Importandroid.content.Intent;Importandroid.content.ServiceConnection;ImportAndroid.os.IBinder;Importandroid.os.RemoteException;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.util.Log;Importjava.util.List;ImportMy.itgungnir.aidl.Book;ImportMy.itgungnir.aidl.IBookManager; Public classMainactivityextendsappcompatactivity {Private Static FinalString TAG = "Mainactivity"; PrivateServiceconnection connection =Newserviceconnection () {@Override Public voidonserviceconnected (componentname name, IBinder service) {Ibookmanager Manager=IBookManager.Stub.asInterface (service); Try {                //Search All BooksList<book> Booklist =manager.getbooklist (); LOG.I (TAG,"Query Book list:" +booklist.tostring ()); //Add new bookBook Newbook =NewBook ("Html", 40);                Manager.addbook (Newbook); LOG.I (TAG,"Add Book:" +newbook.tostring ()); //Search All BooksBooklist =manager.getbooklist (); LOG.I (TAG,"Query Book list:" +booklist.tostring ()); } Catch(RemoteException e) {e.printstacktrace (); }} @Override Public voidonservicedisconnected (componentname name) {}}; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Intent Intent=NewIntent (); Intent.setaction ("My.itgungnir.aidl.book_server"); Intent.setpackage ("My.itgungnir.server");    Bindservice (Intent, connection, context.bind_auto_create); } @Overrideprotected voidOnDestroy () {unbindservice (connection); Super. OnDestroy (); }}

Since the server and the client are placed in two different module, the package name for the intent object needs to be set to the service side.

As you can see, on the client side, we call the Getbooklist () method on the server, fetch the book object stored in the server's list and print it to the console via log logs. In this way, we can see the printed information in the console as follows:

My.itgungnir.client i/mainactivity:query Book list: [book{booname= ' Android ', pirce=20}, Book{booname= ' IOS ', pirce=17} ]my.itgungnir.client i/mainactivity:add book:book{booname= ' Html ', pirce=40}my.itgungnir.client I/MainActivity: Query book list: [book{booname= ' Android ', pirce=20}, Book{booname= ' IOS ', pirce=17}, Book{booname= ' Html ', pirce=40}]

Introduction to the Aidl of "ANDROID-IPC"

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.