1. 程式人生 > >android Aidl 實現程序間通訊

android Aidl 實現程序間通訊

1​,android 新建aidl 檔案 刪除void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString);這個方法沒用到 還需要實現。

2,新增自己需要的方法例如

package com.cglt.cutticket;

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

interface CgltechAidl {
     int getApkVersionCode();
}

3,定義Service,定內部類CgltehcBinder 實現Aidl介面,並且onBind返回實現類

public class AidlService extends Service {
    class CgltehcBinder extends CgltechAidl.Stub {
        public CgltehcBinder() {
            Log.e("biner", "biner");
        }

        @Override
        public int getApkVersionCode() throws RemoteException {
            return AppInfo.apkVerisonCode;
        }

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new CgltehcBinder();
    }
}

4,配置Service,action為CgltechAidlAction

<service android:name=".AidlService">
    <intent-filter>
        <action android:name="CgltechAidlAction"></action>
    </intent-filter>
</service>

5,另一個apk繫結這個service

Intent intent = new Intent();
intent.setAction("CgltechAidlAction");//Service的action
intent.setPackage("com.cglt.cutticket");//Service 所在包名
bindService(intent, new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Log.e("fff","ok");
        cgltechAidl = CgltechAidl.Stub.asInterface(service);
        try {
            Log.e("fff",cgltechAidl.getApkVersionCode()+"/");
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.e("fff","no");
    }
}, BIND_AUTO_CREATE);