天天看點

AIDL的一般寫法

AIDL是很老的知識點了,網上資料一大堆,查查資料看看就明白了,但是一段時不用就忘了,故此篇部落格記錄一下AIDL的一般寫法,以備不時之需。

下面開始

aidl是應用程式間進行通信的一個橋梁,一般需要一個Service充當服務端,另外一個應用綁定這個Service,并且通過binder驅動來調用服務端提供的方法。Service在綁定的時候需要傳回一個IBinder對象,故綁定service的目的也是架通用戶端與服務端的橋梁—IBinder。
  • 服務端:
廢話不多說,當時要先建一個aidl檔案,方法是在main目錄下建立一個aidl目錄(java同級目錄),然後随便寫一個包名,然後再用AndroidStudio建立一個aidl檔案(注意本篇介紹都是基于AndroidStudio)。
package com.zhg.demo.aidl;

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

interface ICalcInterface {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
            double aDouble, String aString);


    int add(int a,int b);
    int sub(int a,int b);
}
           

basicTypes()這個方法是建立檔案時的預設方法,不去管它。你删掉即可

服務端是一個service,主要重寫onBind()方法代碼如下:
@Override
    public IBinder onBind(Intent intent) {
        Log.e("info","aidl.Server.onBind()=============");
        return myBinder;
    }
           
myBinder的代碼在此:
private ICalcInterface.Stub myBinder=new ICalcInterface.Stub() {
        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

        }

        @Override
        public int add(int a, int b) throws RemoteException {
            return a+b;
        }

        @Override
        public int sub(int a, int b) throws RemoteException {
            return a-b;
        }
    };
           
還有一部,注冊這個Service,AndroidManifest配置如下:
<service android:name=".CalcService" android:enabled="true" android:exported="true">
            <intent-filter >
                <action android:name="com.zhg.demo.aidl.service"></action>
                <category android:name="android.intent.category.DEFAULT"></category>
            </intent-filter>
        </service>
           

注意我們給這個Service設定了一個Action,在用戶端就通過這個Action來啟動此Service

服務端完成,接着進行用戶端代碼編寫
  • 用戶端
用戶端也是建立一個aidl檔案,你可以把這個東東了解成一個接口,規範并提供了一組方法供用戶端調用。注意aidl的包名與檔案名必須與服務端的aidl的保持一緻。
package com.zhg.demo.aidl;

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

interface ICalcInterface {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
            double aDouble, String aString);

    int add(int a,int b);
    int sub(int a,int b);
}
           

接下來就用戶端綁定service,調用服務的方法,首先來看下啟動service的代碼,都是些正常代碼:

綁定service

Intent intent=new Intent("com.zhg.demo.aidl.service");
            bindService(intent,mServiceConnection , Context.BIND_AUTO_CREATE);
           
mServiceConnection對象在此:
private ICalcInterface iCalcInterface;

private ServiceConnection mServiceConnection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.e("info","aidl.Client.onServiceConnected()======");
            iCalcInterface=ICalcInterface.Stub.asInterface(iBinder);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.e("info","aidl.Client.onServiceDisconnected()==========");
            iCalcInterhljs-keyword">null;
        }
    };
           
調用加法運算方法
if(iCalcInterface!=null){
                try {
                    int result=iCalcInterface.add(,);
                    Toast.makeText(MainActivity.this,"result="+result,Toast.LENGTH_SHORT).show();
                } catch (RemoteException e) {
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();

                }
            }else{
                Toast.makeText(MainActivity.this,R.string.tips,Toast.LENGTH_SHORT).show();
            }
           
減法運算類似,故略

注意:bindService後,即使unbind了service,還是能調用Server提供的服務的,除非在背景強行停止程式。

源碼位址:https://github.com/naiyizhang/BlogDemo

AIDLServer和AIDLClient子產品