Android Studio creates aidl files and enables interprocess communication

Source: Internet
Author: User

In Android, cross-process communication is a very common thing, it uses the binder mechanism to process the interaction between processes. The binder mechanism will open up some interfaces to the Java layer for the Android developer to communicate between processes. These interfaces are packaged into the Aidl file, and when our project is used for cross-process communication, the. aidl file can be created, and the. aidl file can assist us in achieving cross-process communication. The following is a brief introduction to the process of creating a Aidl file with Androidstudio.

A. Create a new Aidl file

1. project folder right-click---> New---> select aidl



2. Customizing an Interface name



3. After the creation we see the Xxx.aidl file, and then edit the method that the project needs to implement, here is a simple way to get a string getallname.



4. After writing, we need to re-rebuild, after the project build/generated/source/aidl/debug/package to see the system for us to generate the name of the just. aidl file name of the Java file.



The Java file system generates code automatically:

Stub: Describes a Java service that corresponds to a remote server.

Proxy: Describes the agent object for a Java service, which is obtained on the client side.

Both of these implement the Ipersonmanager interface.

Asinterface: The proxy object of the Java service, which is a binderproxy, is encapsulated into a IPersonManager.Stub.Proxy object, which implements the Ipersonmanager interface.

Ontransact: Responsible for receiving communication between the distribution processes.   It will first receive a request from the client, different methods into the corresponding case code, and then to the stub subclass to handle the event, such as java.lang.String _result = This.getallname (); This will allow its subclass to receive the request and process it.

IBinder Transact method: used to send inter-process requests.


B. Using AIDL to achieve inter-process communication

One: The interface file contains only the underlying data type

As in the Aidl file, only the basic data types are used in the Ipersonmanager, and a new service is required to complete the small project on the server side.

The server-side code is as follows

public class Personservice extends Service {    private static String names = "Alice & Iland";    Public Personbinder Mpersonbinder;    @Override public    void OnCreate () {        super.oncreate ();        Mpersonbinder = new Personbinder ();    }    @Override public    IBinder onbind (Intent Intent) {        return mpersonbinder;    }    public class Personbinder extends ipersonmanager.stub{        @Override public        String Getallname () throws remoteexception {            return names;}}    }

Inheriting the service of the system and building an inner class to inherit ipersonmanager.stub, here is very simple, when the client requests to get the name when we give names to the client here.


Client-side code is as follows

public class Mainactivity extends appcompatactivity implements view.onclicklistener{private static final String TAG =    "Mainactivity";    Private Button Btnget;    Private EditText etshow;    Public Ipersonmanager Mipersonmanager; Serviceconnection sc = new Serviceconnection () {@Override public void onserviceconnected (componentname name            , IBinder service) {log.i (TAG, "onserviceconnected:");        Mipersonmanager = IPersonManager.Stub.asInterface (service); } @Override public void onservicedisconnected (componentname name) {log.i (TAG, "Onservicedisconne            CTED: ");        Mipersonmanager = null;    }    };        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Btnget = (Button) Findviewbyid (r.id.btn_getname);        Etshow = (EditText) Findviewbyid (R.ID.ET_ALLNAMEF); Btnget.setonclicklistener (This);        Intent Intent = new Intent ("Com.ly.testaidlserver.aidl.AIDL_SERVICE");        Intent.setpackage ("Com.ly.testaidlserver");    Bindservice (INTENT,SC, service.bind_auto_create);                } @Override public void OnClick (View v) {switch (V.getid ()) {r.id.btn_getname:                String names = null;                try {if (mipersonmanager!=null) names = Mipersonmanager.getallname ();                } catch (RemoteException e) {e.printstacktrace ();                } etshow.settext (names);            Break        Default:break;        }} @Override protected void OnDestroy () {Super.ondestroy ();    Unbindservice (SC); }}

In the Onserviceconnected method get Ipersonmanager proxy object, finally get to Alice & Ilan, and the server side data consistent.


Attention:

The 1.bindService method changes after 5.0, with implicit intent to set the package or commponent, directly defining an action to report an exception.

        Intent Intent = new Intent ("Com.ly.testaidlserver.aidl.AIDL_SERVICE");        intent.setpackage ("Com.ly.testaidlserver");        Bindservice (INTENT,SC, service.bind_auto_create);

2. We need to copy the server-side Aidl file to the client side, and the folder that holds the Aidl in the client also needs to match the server-side package name.


For the path that the Aidl file stores on the server side, the path to the client-side aidl file is consistent, so the client side needs to create a new package for the server-side packet name.

3. When we start the project, if in the activity Ipersonmanager cannot find the report exception, please add the Aidl file in the app's build.gradle to the naming directory, as in this example,

sourcesets{
Main {
Aidl.srcdirs = [' Src/main/aidl ', ' Src/main/java ']
}
}


Two: The interface file contains complex data types,

1. Creating a new person.aidl content is simple

Parcelable person;

2. Create a new person entity class, in order to be able to communicate between processes must implement the Parcelable interface.

3. A method has been added to Ipersonmanager to note that the person class used must have the package name Improt in.

4. Copy the Ipersonmanager.aidl, Person.aidl, Person.java to the client's Aidl package.

5. See if you need to modify SOUrcesets settings in Build.gradle


The code basically does not change:


Person.java

public class Person implements parcelable {String name;    int age;        Public person (String name, Int. age) {this.name = name;    This.age = age; public static final creator<person> Creator = new creator<person> () {@Override public Pers        On Createfromparcel (Parcel in) {return new person (in.readstring (), In.readint ());        } @Override Public person[] NewArray (int size) {return new person[size];    }    };    @Override public int describecontents () {return 0;        } @Override public void Writetoparcel (Parcel dest, int flags) {dest.writestring (name);    Dest.writeint (age);    } public String GetName () {return name;    } public void SetName (String name) {this.name = name;    } public int Getage () {return age;    public void Setage (int.) {this.age = age; }}

Ipersonmanager.aidl

Interface Ipersonmanager {   String getallname ();   List<person> getpersonlist ();}


Server

public class Personservice extends Service {    private list<person> persons = new arraylist<person> ();    Public Personbinder Mpersonbinder;    @Override public    void OnCreate () {        super.oncreate ();        Mpersonbinder = new Personbinder ();        person P1 = new Person ("Alice", at $);        Persons.add (p1);        person P2 = new Person ("Iland",);        Persons.add (p2);    }    @Override public    IBinder onbind (Intent Intent) {        return mpersonbinder;    }    public class Personbinder extends ipersonmanager.stub{        @Override public        String Getallname () throws remoteexception {            return "";        }        @Override public        list<person> getpersonlist () throws RemoteException {            return persons;        }    }


Clent

public class Mainactivity extends appcompatactivity implements view.onclicklistener{private static final String TAG =    "Mainactivity";    Private Button Btnget;    Private EditText etshow;    Public Ipersonmanager Mipersonmanager; Serviceconnection sc = new Serviceconnection () {@Override public void onserviceconnected (componentname name            , IBinder service) {log.i (TAG, "onserviceconnected:");        Mipersonmanager = IPersonManager.Stub.asInterface (service); } @Override public void onservicedisconnected (componentname name) {log.i (TAG, "Onservicedisconne            CTED: ");        Mipersonmanager = null;    }    };        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Btnget = (Button) Findviewbyid (r.id.btn_getname);        Etshow = (EditText) Findviewbyid (R.ID.ET_ALLNAMEF); Btnget.setonclicklistener (This);        Intent Intent = new Intent ("Com.ly.testaidlserver.aidl.AIDL_SERVICE");        Intent.setpackage ("Com.ly.testaidlserver");    Bindservice (INTENT,SC, service.bind_auto_create);                } @Override public void OnClick (View v) {switch (V.getid ()) {r.id.btn_getname:                arraylist<person> persons = NULL; try {if (mipersonmanager!=null) persons = (arraylist<person>) Mipersonman                Ager.getpersonlist ();                } catch (RemoteException e) {e.printstacktrace ();                } String result = "";                for (person person:persons) {result = Result+person.getname () + "__" +person.getage ();                } etshow.settext (Result);            Break        Default:break;        }} @Override protected void OnDestroy () {Super.ondestroy ();   Unbindservice (SC); }} 









Android Studio creates aidl files and enables interprocess communication

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.