Android Development Step by Step 62: The Aidl of interprocess communication

Source: Internet
Author: User
Tags mremote

Android process communication between, such as an app and another app interaction, there are several ways, there are 1, the activity of the Jump 2, ContentProvider 3, broadcast 4, Aidl, personally think the front 3 is relatively simple, The application scenario is not the same. This article studies the use of aidl for communication between processes.

Aidl full name is the Android Interface definition Language, that is, the interface definition language, as I understand, this actually and. Net,java inside the WebService similar, WebService also has a WSDL Web Services Description Language, a server that automatically generates proxy classes by defining interfaces. The client then uses this proxy class to invoke the corresponding service on the server side. The Android Aidl is implemented by binding service services. This article has written a demo, has been doing third-party payment, here to simulate the third-party payment scenario, the payment app (server) provides a AIDL payment interface to the app (client) to call the completion of the payment function.

First step: service-side definition payment Interface Aidltestinterface.aidl

/** *  */package com.figo.study.aidl;/** * @author Figo * */interface aidltestinterface {    int pay (String orderid,s Tring productname,float money);}

Then you see that the stub proxy class is automatically generated under the Gen folder.

/* * This file is auto-generated. Do not MODIFY. * Original File:e:\\projects\\study\\src\\com\\figo\\study\\aidl\\aidltestinterface.aidl */package com.figo.study.aidl;/** * @author Figo * */public interface Aidltestinterface extends android.os.iinterface{/** Local-side IPC implementation stub class. */public static abstract class Stub extends Android.os.Binder implements Com.figo.study.aidl.aidltestinterface{private Static final Java.lang.String descriptor = "Com.figo.study.aidl.AidlTestInterface";/** Construct the stub at attach it to The interface. */public Stub () {this.attachinterface (this, descriptor);} /** * Cast an IBinder object to an Com.figo.study.aidl.AidlTestInterface interface, * Generating a proxy if needed. */public static Com.figo.study.aidl.AidlTestInterface asinterface (Android.os.IBinder obj) {if ((Obj==null)) {return null;} Android.os.IInterface iin = obj.querylocalinterface (descriptor); if ((Iin!=null) && (iin instanceof Com.figo.study.aidl.AidlTestInterface))) {return ((com.figo.study.aidl.AidlTestInterface) iin);} return new Com.figo.study.aidl.AidlTestInterface.Stub.Proxy (obj); @Override public Android.os.IBinder Asbinder () {return this;} @Override public boolean ontransact (int code, ANDROID.OS.PARCEL data, android.os.Parcel reply, int flags) throws ANDROID.O S.remoteexception{switch (code) {case interface_transaction:{reply.writestring (descriptor); return true;} Case Transaction_pay:{data.enforceinterface (descriptor); java.lang.String _arg0;_arg0 = data.readstring (); Java.lang.String _arg1;_arg1 = data.readstring (); Float _arg2;_arg2 = Data.readfloat (); int _result = This.pay (_arg0, _ Arg1, _ARG2); Reply.writenoexception (); Reply.writeint (_result); return true;}} Return Super.ontransact (Code, data, reply, flags);} private static class Proxy implements Com.figo.study.aidl.aidltestinterface{private Android.os.IBinder Mremote; Proxy (Android.os.IBinder remote) {mremote = remote;} @Override public Android.os.IBinder Asbinder () {return mremote;} Public java.lang.StRing Getinterfacedescriptor () {return descriptor;} @Override public int Pay (java.lang.String orderId, java.lang.String productName, float money) throws Android.os.remoteexception{android.os.parcel _data = Android.os.Parcel.obtain (); Android.os.Parcel _reply = Android.os.Parcel.obtain (); int _result;try {_data.writeinterfacetoken (descriptor); _data.writestring (orderId); _ Data.writestring (ProductName); _data.writefloat (money); Mremote.transact (Stub.transaction_pay, _data, _reply, 0); _ Reply.readexception (); _result = _reply.readint ();} finally {_reply.recycle (); _data.recycle ();} return _result;}} static final int transaction_pay = (Android.os.IBinder.FIRST_CALL_TRANSACTION + 0);} public int Pay (java.lang.String orderId, java.lang.String productName, float money) throws android.os.RemoteException;}

Step Two: server defines a service implementation payment interface

/** * */package Com.figo.study.aidl;import Android.app.service;import Android.content.intent;import Android.os.IBinder;import    Android.os.remoteexception;import android.util.log;/** * @author Figo * */public class Aidltestservice extends Service {    String tag = "Aidltestservice"; Private Aidltestinterface.stub Mbinder = new Aidltestinterface.stub () {@Override public int pay (String Orde  RId, String productName, float money) throws RemoteException {System.out.print ("received the data requested by the client:" + orderId + "," +            ProductName + "," + money);            LOG.I (Tag, "received the data requested by the client:" + orderId + "," + ProductName + "," + Money ");        return 1;    }    }; /* (non-javadoc) * @see android.app.service#onbind (android.content.Intent) */@Override public IBinder Onbin    D (Intent Intent) {//TODO auto-generated method stub return mbinder; }}

The third step, service-side registration services

    <service android:name= ". Aidl. Aidltestservice ">            <intent-filter>                <action android:name=" Com.figo.study.aidl.service "/>                <category android:name= "Android.intent.category.DEFAULT"/>            </intent-filter>    </ Service>

OK, so-called service end, has been completed, the following start the client's work.

The fourth step, the server automatically generated stub class (that is, the Aidl file generated to the Gen folder under the class) into a jar, add to the Client Libs folder, this step can also be written in the client under the same name of the Aidl file to complete.

The fifth step, the client invokes the payment interface on the server through Aidl

/** * */package com.study.aidlclient;import com.figo.study.aidl.aidltestinterface;import android.app.Activity; Import Android.content.componentname;import Android.content.context;import Android.content.intent;import Android.content.serviceconnection;import Android.os.asynctask;import Android.os.bundle;import Android.os.IBinder; Import Android.os.remoteexception;import Android.util.log;import Android.view.view;import Android.view.view.onclicklistener;import android.widget.button;/** * @author Figo * */public class    Aidltestclientactivity extends Activity {private Button btnpay;    Aidltestinterface Maidltestinterface;    String tag = "Aidltestclientactivity"; Private Serviceconnection mconnection = new Serviceconnection () {public void onserviceconnected (ComponentName clas            SName, IBinder service) {maidltestinterface = AidlTestInterface.Stub.asInterface (service);                try {log.i (tag, "Onserviceconnected,start to pay!"); New PaytAsk (). Execute (1);            } catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();        }} public void onservicedisconnected (ComponentName className) {maidltestinterface = null;    }    }; @Override protected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method stub super.o        Ncreate (savedinstancestate);        Setcontentview (r.layout.activity_aidltest);        Btnpay = (Button) Findviewbyid (R.id.btn_pay);                Btnpay.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {            Pay ();    }        }); } class Paytask extends Asynctask<integer, Integer, boolean> {@Override protected Boolean Doinback            Ground (Integer ... params) {//TODO auto-generated method Stub int result = 0; try {result = Maidltestinterface.pay ("1234567890 "," Shangrao chicken Leg ", 10f);            } catch (RemoteException e) {//TODO auto-generated catch block E.printstacktrace ();            } if (result = = 1) {LOG.I (tag, "pay successful!");        } return true;            } @Override protected void OnPostExecute (Boolean result) {//TODO auto-generated method stub            Super.onpostexecute (result);            Payment Complete Unbind Service Unbindservice (mconnection);        LOG.I (Tag, "Unbindservice successful!");    }    };        private void Pay () {Intent Intent = new Intent ("Com.figo.study.aidl.service");        Add PackageName to avoid implicit intents with StartService is not safe intent.setpackage ("Com.figo.study");    Bindservice (Intent, mconnection, context.bind_auto_create); }}

Android Development Step by Step 62: The Aidl of interprocess communication

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.