The simplest Android Aidl to use

Source: Internet
Author: User

First, why use Aidl

--------------------------------------------------------------------------------------------------------------- ------------

Aidl is actually communication between processes.official documentation specifically reminds us of when it is necessary to use AIDL: Only you allow clients to access your service from different applications for interprocess communication, as well as to handle multithreading in your service. If you do not need to perform concurrent communication between different applications (IPC), you should create your interface by implementing a Binder, or if you want to do IPC but do not need to process multithreading, then implement your Interface using a Messenger
Simply put , 1, you have a service to be used by others, 2, you want to use the service of other processes
then, how to use the Aidl (one of the simplest uses, get a string from the server)-------------------------------------------------------------------------steps:Service Side1, set up the xxx. aidl file in the service terminal, put the interface (this interface is the same as the file name), the same way as the Java program2, create a new service, the service inside the Aidl file to implement the interface 3. manifest.xml file Registration Service Client Side1, copy before the Aidl file (to be independent of the server folder with the same name of the folder, or the error will be the most later)2. Initialize the serviceconnection (for bind service) in activity, and get service on the server Service = interface on the server side . Stub.asinterface (service);// serviceconnection in the onserviceconnected 3, Bindservice
Implementation code:Check the directory structure first

Executemyaidlservice.aidl file (Note that the interface name is the same as the file name)
Package Aid;interface Executemyaidlservice {String SayHello ();}
Myaidlservice.java file
Package Aidlservice;import aid. Executemyaidlservice;import Android.app.service;import Android.content.intent;import Android.os.IBinder;import Android.os.remoteexception;public class Myaidlservice extends service{private static final String TAG = "Myaidlservice"; Private Executemyaidlservice.stub Mbinder = new Executemyaidlservice.stub () {@Overridepublic String SayHello () throws remoteexception {//TODO auto-generated method Stubreturn "Hello";}        }; @Overridepublic ibinder onbind (Intent Intent) {//TODO auto-generated method Stubreturn Mbinder;} private void Log (String str) {          android.util.log.d (TAG, "------" + str + "------");      }      @Override public      void OnCreate () {          Log ("service create");      }      @Override public      void OnStart (Intent Intent, int startid) {          Log ("service start id=" + Startid);      }          }
There's nothing in the activity, not a sticker.
The directory structure of the client


Clientactivity's Code:
Package Com.example.aidlclienttest;import aid. Executemyaidlservice;import Android.support.v7.app.actionbaractivity;import Android.content.componentname;import Android.content.intent;import Android.content.serviceconnection;import Android.os.bundle;import Android.os.ibinder;import Android.os.remoteexception;import Android.view.menu;import Android.view.MenuItem;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.textview;public class Clientactivity extends Actionbaractivity {private Executemyaidlservice   Miaidlserverservice = null;  Private TextView Mtextview = null; Private Button Mbutton = null; Private Serviceconnection mconnection = new Serviceconnection () {public void onservicedisconnected (Compo          Nentname name) {miaidlserverservice = null; } public void onserviceconnected (componentname name, IBinder service) {Miaidlserverservice = Exe Cutemyaidlservice.sTub.asinterface (service);            Aidl communication try {String mText = "Say Hello:" + Miaidlserverservice.sayhello ();            Mtextview.settext (MText);              } catch (RemoteException e) {e.printstacktrace ();      }          }      };        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_client);        Mtextview = (TextView) Findviewbyid (R.id.helloword);        Mbutton = (Button) Findviewbyid (R.ID.GETSERVICEFROMAIDL); Mbutton.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method Stubintent service = new Intent ("Aidl. Executemyaidlservice "); Service.setaction (" Aidl.                Executemyaidlservice "); Bindservice (service, mconnection,bind_auto_create);    }                }); } @Override Public boolean Oncreateoptionsmenu (Menu menu) {//inflate the menu; this adds items to the action bar if it is present.        Getmenuinflater (). Inflate (r.menu.client, menu);    return true; } @Override public boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here.  The action bar would//automatically handle clicks on the Home/up button, so long/As you specify a parent        Activity in Androidmanifest.xml.        int id = item.getitemid ();        if (id = = r.id.action_settings) {return true;    } return super.onoptionsitemselected (item); }}

Here is the simplest way to aidl communication. Look at the effect first open the server

then start the client side and click Bindservice

Advanced Aidl---------------------------------------------------------------------------------------------1. What if I want to get an object from the service? (most to be applied)implementing an Object Parcelable interface Write a Aidl file for this object [it only needs to define this object as follows:]
Parcelable Object

Just look at the code.Let's take a look at this structure.Add a class of person, this class to implementParcelable InterfaceCode
Package Aid;import Android.os.parcel;import Android.os.parcelable;import Android.os.parcelable.creator;public class     Person implements parcelable{private String Name;private int age;    Private String Place;        Public person (Parcel source) {//TODO auto-generated Constructor stubname = source.readstring ();        Age = Source.readint (); Place = Source.readstring ();} @Overridepublic String toString () {return "person [name=" + name + ", age=" + Age + ", place=" + place+ "]";} Public person () {//TODO auto-generated constructor stub}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;} Public String Getplace () {return-place;} public void Setplace (String place) {this.place = place;} @Overridepublic int describecontents () {//TODO auto-generated method Stubreturn 0;} @Overridepublic void Writetoparcel (Parcel dest, int flags) {//TODO auto-generated method Stubdest.writestring (name);        Dest.writeint (age); Dest.writestring (place);} public static final parcelable.creator<person> Creator = new creator<person> () {@Overridepublic person            Createfromparcel (Parcel source) {//TODO auto-generated method Stubperson person = new person (source); return person;} @Overridepublic person[] NewArray (int size) {//TODO auto-generated method Stubreturn new Person[size];}};}
Also write a aidl file
I want to add an empty function to get the object from the previous interface .
implemented in the service, the steps are not as much described as before
So that you can get this object from the client side.2. What if the activity is going to pass data to the service? "If the object is the same as the parcelable, (because the client and server's Aidl file is the same)" to add an in to an interface function Basic Types (Int,long,char,boolean, etc.), string,charsequence,list,map, other types must be imported using import, even though they may be in the same package, such as the person above, although it and imyservice in the same package, but still need to display the import in.
In addition, the parameters in the interface, in addition to the types supported by the AIDL, must be identified by the other types: input or output, or both kanehide, with In,out or InOut as the general in tag, as in most cases the input parameter.

This is also very simple: the process is a client side to serversevice incoming an object, service to the object processing, notify or return to the client
Paste the key codeClient Side
private serviceconnection mconnection = new Serviceconnection () {public VO          ID onservicedisconnected (componentname name) {miaidlserverservice = null; } public void onserviceconnected (componentname name, IBinder service) {Miaidlserverservice = Exe              CuteMyAidlService.Stub.asInterface (service);            Aidl communication try {String mText = "Say Hello:" + Miaidlserverservice.sayhello ();            Person Mperson = Miaidlserverservice.getdefaultperson ();            System.out.println (Mperson); Mperson.setage (Mperson.getage () +1); 
<span style= "White-space:pre" ></span>//here to the service incoming object            Miaidlserverservice.tellmehowoldami ( Mperson,mclientcallback);            Mtextview.settext (MText);            } catch (RemoteException e) {                  e.printstacktrace ();              }          }      

We're going to implement callback here.
Clientcallback.stub mclientcallback = new Clientcallback.stub () {<span style= "White-space:pre" ></span> <span style= "White-space:pre" ></span> @Override <span style= "White-space:pre" ></span> public void Handlebyserver (String param) throws remoteexception {<span style= "White-space:pre" ></span>// TODO auto-generated method Stub<span style= "White-space:pre" ></span>toast.maketext ( Getapplicationcontext (), Param, Toast.length_long). Show (); <span style= "White-space:pre" ></span>}< Span style= "White-space:pre" ></span>};

Service side
@Overridepublic String Tellmehowoldami (person Person,clientcallback mclientcallback) throws RemoteException {//TODO Auto-generated Method stubmcallback = Mclientcallback;mcallback.handlebyserver ("Your Is" +string.valueof ( Person.getage ())); return string.valueof (Person.getage ());}        ;


Errors encountered in the process----------------------------------------------------------------------------------------------------------------- -------------------------------Java.lang.SecurityException:Binder invocation to an incorrect interface

There are. aidl files on both the service and client side, so be sure to put them in a separate package because the package names of the mainactivity in the two apps are different, resulting in two. aidl file contents. A single package, with only the. aidl file, guarantees that the package name and file contents are the same.


The simplest Android Aidl to use

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.