Android高手進階(一)AIDL跨進程調用

Android高手進階(一)AIDL跨進程調用

什麼是ADIL跨進程調用?java

    因爲Android是不容許兩個進程共享內存空間的,因此若是當前你開發的應用須要調用其餘應用的某個邏輯處理某個事情的時候,就須要用到AIDL跨進程調用。android

AIDL能幹什麼?app

    APP與APP之間的邏輯交互ide

AIDL開發的步驟?gradle

    服務端ui

    一.新建一個AIDL文件


 

    二.定義接口方法

// IMyAidlInterface.aidl
package com.tcl.personalcloudaidljar;this

import com.tcl.personalcloudaidljar.StudentModel;spa

// Declare any non-default types here with import statements對象

interface IMyAidlInterface {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    double doCalulate(double a,double b);
    double doMin(double a, double b);
    void setStudent(in StudentModel model);
    StudentModel getFinalStudent(inout StudentModel model);
    List<StudentModel> getStudentResult(inout List<StudentModel> model);
}接口

能夠傳的值有JAVA基本類型和List、Map,其餘自定義類型的Model須要指明是in、out、inout之中的一種,分別表示輸入、輸出、和同時輸入和輸出。
若是是自定義類型的Model,須要序列化,實現Parcelable或者Serializable接口,建議實現Parcelable接口(效率更高)。

還須要定義一個Model類名同樣的aidl接口,內容爲

// Student.aidl
package com.tcl.personalcloudaidljar;

parcelable StudentModel;

 

Model類的具體實現見下圖

package com.tcl.personalcloudaidljar;

import android.os.Parcel;
import android.os.Parcelable;

/**
 * Created by pcgu on 16-2-1.
 */
public class StudentModel implements Parcelable {
    private int id;
    private String name;
    private long md5;
    private boolean canShow;

    public StudentModel() {
    }

    private StudentModel(Parcel in) {
        readFromParcel(in);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public long getMd5() {
        return md5;
    }

    public void setMd5(long md5) {
        this.md5 = md5;
    }

    public boolean isCanShow() {
        return canShow;
    }

    public void setCanShow(boolean canShow) {
        this.canShow = canShow;
    }

    public static final Creator<StudentModel> CREATOR =
            new Creator<StudentModel>() {
                @Override
                public StudentModel createFromParcel(Parcel source) {
                    return new StudentModel(source);
                }

                @Override
                public StudentModel[] newArray(int size) {
                    return new StudentModel[size];
                }
            };

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(id);
        dest.writeString(name);
        dest.writeLong(md5);
        dest.writeByte((byte) (canShow ? 1 : 0));
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public void readFromParcel(Parcel in) {
        id = in.readInt();
        name = in.readString();
        md5 = in.readLong();
        canShow = in.readByte() != 0;
    }

}

全部自定義的Model類必須在aidl類中申明。

 

    三.實現service類

package com.tcl.personalcloudaidljar;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import java.util.List;

/**
 * Created by pcgu on 16-1-29.
 */
public class MyService extends Service {
    private static final String TAG = "TEST";

    private final IMyAidlInterface.Stub mBinder = new IMyAidlInterface.Stub() {
        @Override
        public double doCalulate(double a, double b) throws RemoteException {
            Log.e(TAG, "doCalulate a and b=" + a + "," + +b);
            return a + b;
        }

        @Override
        public double doMin(double a, double b) throws RemoteException {
            return a - b;
        }

        @Override
        public void setStudent(StudentModel model) throws RemoteException {
            Log.e(TAG, "setStudent id =" + model.getId() + " name=" + model.getName() +
                    " md5=" + model.getMd5() + " canShow=" + model.isCanShow());
        }

        @Override
        public StudentModel getFinalStudent(StudentModel model) throws RemoteException {
            Log.e(TAG, "getFinalStudent id =" + model.getId() + " name=" + model.getName() +
                    " md5=" + model.getMd5() + " canShow=" + model.isCanShow());
            model.setName("gupengcheng");
            return model;
        }

        @Override
        public List<StudentModel> getStudentResult(List<StudentModel> model) throws RemoteException {
            Log.e(TAG, "get Student Result =" + model.get(0).getName() +
                    " size ==" + model.size());
            StudentModel singleModel = new StudentModel();
            singleModel.setName("gugugu");
            singleModel.setCanShow(false);
            singleModel.setId(123);
            singleModel.setMd5(1234566);
            model.add(singleModel);
            return model;
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "MyService onCreate");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "MyService onDestroy");
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
        Log.e(TAG, "MyService onRebind");
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(TAG, "MyService onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG, "MyService onBind");
        return mBinder;
    }
}

service類中最重要的是實現IMyAidlInterface.Stub mBinder = new IMyAidlInterface.Stub()抽象類,而且在onBind中返回這個mBinder。

    四.在manifest中申明改service並指定過濾條件

這裏指定的過濾條件是action爲com.tcl.personalcloudaidljar.aidl。

 

    客戶端

    客戶端也就是調用方,調用剛纔的服務端的service中實現的抽象方法來完成某個邏輯。

 

    一.拷貝服務端的aidl包到服務端

這時候make project一次就會在以下目錄中自動生成一個aidl實現類

 

    二.調用服務端的aidl接口的具體實現方法

    有兩種使用方式,分別是activity中直接使用和封裝成Jar包給第三方使用。

(1)直接使用

    bindService,而後經過AIDL類的對象調用service中的具體方法來達到跨進程調用的目的。須要注意的是調用以前必須bindService,在Activity onDestory的時候必須unbindService.

(2)封裝成jar包,實現類以下

package com.tcl.personalcloudaidlclient;

import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.tcl.personalcloudaidljar.IMyAidlInterface;
import com.tcl.personalcloudaidljar.StudentModel;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by pcgu on 16-2-1.
 */
public class PersonalCloudManager {
    private static final String TAG = "PersonalCloudManager";
    private IMyAidlInterface mIMyAidlInterface;
    private static boolean connected = false;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e(TAG, "client onServiceConnected");
            mIMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
            connected = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e(TAG, "client onServiceDisconnected");
            mIMyAidlInterface = null;
            connected = false;
        }
    };

    @TargetApi(4)
    public void bindAidlService(Context context) {
        Intent intent = new Intent();
        intent.setAction("com.tcl.personalcloudaidljar.aidl");
        intent.setPackage("com.tcl.personalcloudaidljar");
        context.bindService(intent, connection, Context.BIND_AUTO_CREATE);

    }

    public void unbindAidlService(Context context) {
        context.unbindService(connection);
    }

    public double doCalculate(double num1, double num2) {
        if (!connected) {
            return 0;
        }
        double result = 0;
        try {
            result = mIMyAidlInterface.doCalulate(num1, num2);
            Log.e(TAG, "client add result ==" + result);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return result;
    }

    public double doMin(double num1, double num2) {
        if (!connected) {
            return 0;
        }
        double result = 0;
        try {
            result = mIMyAidlInterface.doMin(num1, num2);
            Log.e(TAG, "client min result ==" + result);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return result;
    }

    public void setStudentModel(StudentModel model) {
        if (!connected) {
            return;
        }
        try {
            mIMyAidlInterface.setStudent(model);
            Log.e(TAG, "client set Student Model");
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public StudentModel getFinalStudentModel(StudentModel model) {
        if (!connected) {
            return model;
        }
        StudentModel finalStudentModel = new StudentModel();
        try {
            finalStudentModel = mIMyAidlInterface.getFinalStudent(model);
            Log.e(TAG, "client set final Student Model");
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return finalStudentModel;
    }

    public List<StudentModel> getList(List<StudentModel> model) {
        if (!connected) {
            return model;
        }
        List<StudentModel> models = new ArrayList<>();
        try {
            models = mIMyAidlInterface.getStudentResult(model);
            Log.e(TAG, "client set final Student Model");
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return models;
    }

    public boolean isServiceConnected() {
        return connected;
    }
}

    須要注意的是給第三方調用須要提供一個服務綁定成功與否的標誌位,即connected這個參數,第三方纔知道可否調用AIDL的實現方法,只有爲True的時候才能調用。

    三.封裝成Jar包的方法

    在app的build.gradle中添加

task makeJar(type: Copy) {
        delete 'build/libs/aidlsdk.jar'
        from('build/intermediates/bundles/release/')
        into('build/libs/')
        include('classes.jar')
        rename ('classes.jar', 'aidlsdk.jar')
    }

    makeJar.dependsOn(build)

用打包命令 ./gradlew makeJar 便可打包爲紅色標記的名字的jar包


    四.注意問題

    當aidl方法中參數爲回調接口的時候,調用實現類須要用new ***Callback.stub()的方式

相關文章
相關標籤/搜索