Android Development---Aidl

Source: Internet
Author: User

In Android development, multi-process communication is sometimes used, at which point the options are:

1. Bundle: Inter-process communication between four components

2. File sharing: For no concurrency scenarios

3. Messager: Low concurrency for one-to-many even communications, no RPC requirements or no need to return results for RPC requirements

4. Aidl: One-to-many communication with RPC requirements

5. Content Provider: One-to-many inter-process data sharing

6. Socket: Network data exchange

Here is an example of using aidl, in fact, the bottom of the message is also aidl to deal with, is a simple package for aidl, Aidl used in the core of an Android system--binder,binder in the Android system to handle inter-process communication, It is based on Openbinder to achieve, is a similar to the COM and CORBA Distributed component architecture, which itself is quite complex, the source has not read, a start to feel foggy, but, first use it, practical help theory, the two are constantly staggered, certainly one day to understand, haha ~

In one app, it's easy to test multi-process communication through the process attribute, and here's another way to use two apps, one for the server and one for the client, in fact, both ways, because for different components of the same application, if they run in different processes, There is no essential difference between them and the two applications that belong to each other.

To start the test:

1. New service-side project: Testaidlserver:

  

2. Create a new user management class User.java,aidl you need to use paracelable to serialize and deserialize objects:

Package Cn.linjk.testaidlserver;import android.os.parcel;import android.os.parcelable;/** * Created by LINJK on 06/12/    */public class User implements parcelable{public int userId;    Public String UserName;        Public User (int userId, String userName) {this.userid = UserId;    This.username = UserName;    } @Override public int describecontents () {return 0;        } @Override public void Writetoparcel (Parcel pparcel, int pI) {pparcel.writeint (userId);    Pparcel.writestring (UserName);        public static final parcelable.creator<user> Creator = new parcelable.creator<user> () {@Override        Public user Createfromparcel (Parcel pparcel) {return new User (Pparcel);        } @Override Public user[] NewArray (int pI) {return new USER[PI];    }    };        Private User (Parcel in) {userId = In.readint ();    UserName = In.readstring (); }}

3. Create a new Aidl folder and create a new Aidl interface file:

3.1 New Aidl folder:

      

After the new complete directory structure is as follows:

      

3.2 New Aidl interface file, the user class is used in the interface file, you need to create a new class Aidl file to declare the class, and the interface file needs to display the import of the user class

      

Here are two ways to add a new user and get all current users.

(Minor episode:

After we make a project here, a Java file is generated:

      

Using Aidl to process, we do not have to write binder communication, of course, can also be handwritten, so as to better understand the principle of binder, but beginners are troublesome, all, both can be achieved, The essence of the Aidl file is that the Android system provides us with a tool to quickly implement binders.

4. In order to facilitate aidl development, all and aidl related classes and files into the same package, if the full path of the class is different, the deserialization will fail, the development of the user directly to the client application can be copied, here to put user class in the Aidl sibling directory.

5. Create a new service to implement the Aidl interface method (here for convenience, first prepare two data on the server):

Package Cn.linjk.testaidlserver;import Android.app.service;import Android.content.intent;import android.os.Binder; Import Android.os.ibinder;import Android.os.remoteexception;import Android.support.annotation.nullable;import Java.util.list;import Java.util.concurrent.copyonwritearraylist;import Cn.linjk.testaidlserver.aidl.IUserManager ; Import cn.linjk.testaidlserver.aidl.user;/** * Created by LINJK on 06/12/2016. */public class Serviceusermanager extends service{private static final String TAG = ServiceUserManager.class.getSimple    Name ();    Private copyonwritearraylist<user> musercopyonwritearraylist = new copyonwritearraylist<> (); Private Binder Mbinder = new Iusermanager.stub () {@Override public void AddUser (user user) throws Remoteexc        eption {musercopyonwritearraylist.add (user); } @Override Public list<user> getAllUsers () throws RemoteException {return Musercopyonwrit        Earraylist;    }    }; @OverRide public void OnCreate () {super.oncreate ();        Musercopyonwritearraylist.add (New User (1, "Jim"));    Musercopyonwritearraylist.add (New User (2, "JIM_LINJK"));    } @Nullable @Override public ibinder onbind (Intent pintent) {return mbinder; }}

6. Start the server, found the following error, unable to find the data class?

    

To modify the App/build.gradle file configuration:

    

7. Yes, the server is open to completion.

8. Create a new client project:

    

9. Copy the files under the server's Src/main/aidl file to the same directory path of the client (if the same app is not copied, shared), complete the following:

    

10. Write the connection service-side code:

Because there is a need to connect the server side of the ServiceManager, you need to move the Serviceusermanager class to the Aidl folder, and to ensure that the server project and client project files and their content consistent, the final Aidl folder file is:

    

Package Cn.linjk.testaidlclient;import Android.content.componentname;import Android.content.context;import Android.content.intent;import Android.content.serviceconnection;import Android.os.ibinder;import Android.support.v7.app.appcompatactivity;import Android.os.bundle;import Android.util.log;import java.util.List; Import Cn.linjk.testaidlserver.aidl.iusermanager;import Cn.linjk.testaidlserver.aidl.serviceusermanager;import  Cn.linjk.testaidlserver.aidl.user;public class Mainactivity extends Appcompatactivity {private final static String TAG    = MainActivity.class.getSimpleName ();        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);    Bindservice (New Intent (this, serviceusermanager.class), mserviceconnection, context.bind_auto_create);        } @Override protected void OnDestroy () {unbindservice (mserviceconnection);    Super.ondestroy (); } Private ServicecoNnection mserviceconnection = new Serviceconnection () {@Override public void onserviceconnected (Componentna            Me pcomponentname, IBinder pibinder) {Iusermanager Lviusermanager = IUserManager.Stub.asInterface (Pibinder);                try {list<user> lvuserlist = Lviusermanager.getallusers (); for (user lvuser:lvuserlist) {log.i (TAG, "[user name]:" + Lvuser.username + "and [user ID]:" +                Lvuser.userid);            }} catch (Exception e) {e.printstacktrace ();        }} @Override public void onservicedisconnected (ComponentName pcomponentname) {// }    };}

11. Start the server app first

12. Start the client app again and you can see that the client app can get the data from the server app:

13. Add a button to the client app to add a user data to the server, the interface code is relatively simple, do not write, look at the button's listening part of the code:

Btnadduser.setonclicklistener (New View.onclicklistener () {            @Override public            void OnClick (View pView) {                try {                    user Lvuser = new User (3, "Apple");                    Lviusermanager.adduser (lvuser);                    list<user> lvuserlist = Lviusermanager.getallusers ();                    for (user lvusertmp:lvuserlist) {                        log.i (TAG, "[user name]:" + Lvusertmp.username + "and [user ID]:" + lvusertmp . userId);                    }                }                catch (Exception e) {                    e.printstacktrace ();}}}        );

14. Run the client app again to see the log:

Initially no user ID 3, click the button, once again look at the user list, a new user success:

Here, Aidl's test has been able to, of course, the whole logic has a lot of exceptions not to consider, here is not all perfect, for example, not every time from the server query data, but the server data updated automatically remind the Client interface refresh function.

Code submitted by GitHub: https://github.com/linjk/TestAIDL.git

Android Development---Aidl

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.