Step 62 for android development: Aidl for inter-process communication

Source: Internet
Author: User

Step 62 for android development: Aidl for inter-process communication

Communication between android processes, such as interaction between an app and another app. Which of the following methods are available: 1. activity jump 2. contentprovider 3. broadcast 4. aidl, I personally think that the first three are relatively simple and the application scenarios are different. This article describes how to use aidl to communicate between processes.

The full name of aidl is Android Interface Definition Language, that is, the Interface Definition Language. In my understanding, this actually corresponds.. net, similar to webservice in java, webservice also has a wsdl Web Services Description Language. The server automatically generates a proxy class by defining interfaces. Then the client uses this proxy class to call the corresponding services of the server. Android aidl is implemented by binding a service. This article has written a demo, which has been used for third-party payment before. Here we simulate the third-party payment scenario. The payment app (server) provides an aidl payment interface to the app (client) to call the complete payment function.

Step 1: The server defines the payment interface AidlTestInterface. aidl

 

/** *  */package com.figo.study.aidl;/** * @author figo * */interface AidlTestInterface {    int pay(String orderId,String productName,float money);}

Then, 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 into 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.os.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 2: the server defines a service to implement the 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 orderId, String productName, float money) throws RemoteException {System. out. print ("received client request data:" + orderId + "," + productName + "," + money); Log. I (tag, "received client request data:" + orderId + "," + productName + "," + money); return 1 ;}}; /* (non-Javadoc) * @ see android. app. service # onBind (android. content. intent) */@ Override public IBinder onBind (Intent intent) {// TODO Auto-generated method stub return mBinder ;}}

Step 3: register the service on the server

 

 

    
             
                                  
               
   
      
 

Okay. The so-called server has been completed. Next we will start working on the client.

 

Step 4. compress the Stub class automatically generated by the server (that is, the class in which the aidl file is generated under the gen folder) into jar and add it to the libs folder of the client, this step can also be done by writing an aidl file under the same package name on the client.

Step 5: The client calls the payment interface of 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 className, IBinder service) {m AidlTestInterface = AidlTestInterface. Stub. asInterface (service); try {Log. I (tag, "onServiceConnected, start to pay! "); New paytask(cmd.exe cute (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. onCreate (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
 
  
{@ Override protected Boolean doInBackground (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); // The 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 are not safe intent. setPackage ("com. figo. study "); bindService (intent, mConnection, Context. BIND_AUTO_CREATE );}}
 

 

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.