天天看點

android開發步步為營之62:程序間通信之Aidl

           android程序之間通信,比如一個app和另外一個app互動,有哪幾種方式,主要有1、activity的跳轉  2、contentprovider  3、broadcast  4、aidl,個人認為前面3種相對簡單,應用場景也不一樣。本文研究一下使用aidl進行程序之間的通信。

           aidl全稱是Android Interface Definition Language,即接口定義語言,依我了解,這個其實和.net,java裡面的webservice相似的,webservice也有個wsdl Web Services Description Language,服務端通過定義接口,自動生成代理類。然後用戶端使用這個代理類來調用服務端的相應服務。android aidl是通過綁定服務service來實作的。本文寫了個demo,之前一直做第三方支付,這裡就模拟第三方支付的場景,支付app(服務端)提供一個aidl支付接口給應用app(用戶端)來調用完成支付功能。

         第一步:服務端定義支付接口AidlTestInterface.aidl

/**
 * 
 */
package com.figo.study.aidl;

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

然後看到gen檔案夾下面會自動生成stub代理類了。

/*
 * 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;
}
           

       第二步:服務端定義一個service實作支付接口

/**
 * 
 */
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("收到用戶端請求的資料:" + orderId + "," + productName + "," + money);

            Log.i(tag, "收到用戶端請求的資料:" + 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;
    }
}
           

        第三步、服務端注冊service

<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>
           

        好的,所謂的服務端,已經完成,下面開始用戶端的工作。

        第四步、将服務端自動生成的Stub類(即aidl檔案生成到gen檔案夾下面的那個類)打成jar,添加到用戶端libs檔案夾,這步也可在用戶端寫一個相同包名下的aidl檔案來完成。

        第五步、用戶端通過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) {
            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.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<Integer, Integer, Boolean> {

        @Override
        protected Boolean doInBackground(Integer... params) {
            // TODO Auto-generated method stub
            int result = 0;
            try {
                result = mAidlTestInterface.pay("1234567890", "上饒雞腿", 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);
            //支付完成取消綁定服務
            unbindService(mConnection);
            Log.i(tag, "unbindService successful!");

        }

    };

    private void pay() {
        Intent intent = new Intent("com.figo.study.aidl.service");
        //添加packageName避免Implicit intents with startService are not safe
        intent.setPackage("com.figo.study");
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }
}
           

繼續閱讀