Android 車載應用開發(fā)與分析 (4)- 編寫基于AIDL 的 SDK

前言

之前介紹了車載應用開發(fā)體系中如何使用Jetpack在HMI中構建MVVM架構Android 車載應用開發(fā)與分析 (3)- 構建 MVVM 架構(Java版),通過之前的介紹,也了解到在大多數車載系統(tǒng)應用架構中,一個完整的應用往往會包含三層,分別是

  • HMI
    Human Machine Interface,顯示UI信息,進行人機交互。

  • Service
    在系統(tǒng)后臺進行數據處理,監(jiān)控數據狀態(tài)。

  • SDK
    根據業(yè)務邏輯,需要Service對外暴露的通信接口,其他模塊通過SDK來完成與Service通信,通常是基于AIDL接口。

本篇主要講解,如何編寫基于 AIDL 的 SDK 。

AIDL 介紹

AIDL,Android 接口定義語言,是Android開發(fā)中常用的一種進程間通信方式。關于如何使用 AIDL 請參考 Android 接口定義語言 (AIDL) | Android 開發(fā)者 | Android Developers

這里介紹一些 AIDL 使用過程中容易混淆的關鍵字:

  • in
interface HvacInterface {
    void setData(in Hvac hvac);
}

單向數據流向。被in修飾的參數,會順利傳到Server端,但Servier端對實參的任何改變,都不會回調給Client端。

  • out
interface HvacInterface {
    void getData(out Hvac hvac);
}

單向數據流向。被out修飾的參數,只有默認值會傳到Server端,Servier端對實參的改變,在調用結束后,會回調給Client端。

  • inout
interface HvacInterface {
    void getData(inout Hvac hvac);
}

inout 則是上面二者的結合,實參會順利傳到Server,且Server對實參的修改,在調用結束后會返回Client端。

  • oneway
    AIDL 定義的接口默認是同步調用。舉個例子:Client端調用setData方法,setData在Server端執(zhí)行需要耗費5秒鐘,那么Client端調用setData方法的線程就會被block5秒鐘。如果在setData方法上加上oneway,將接口修改為異步調用就可以避免這個問題。
interface HvacInterface {
    oneway void setData(in Hvac hvac);
}

oneway不僅可以修飾方法,也可以用來修飾在interface本身,這樣interface內所有的方法都隱式地帶上oneway。被oneway修飾了的方法不可以有返回值,也不可以再用out或inout修飾參數。

AIDL 常規(guī)用法

IRemoteService iRemoteService;

private ServiceConnection mConnection = new ServiceConnection() {
    // Called when the connection with the service is established
    public void onServiceConnected(ComponentName className, IBinder service) {
        // Following the example above for an AIDL interface,
        // this gets an instance of the IRemoteInterface, which we can use to call on the service
        iRemoteService = IRemoteService.Stub.asInterface(service);
    }

    // Called when the connection with the service disconnects unexpectedly
    public void onServiceDisconnected(ComponentName className) {
        Log.e(TAG, "Service has unexpectedly disconnected");
        iRemoteService = null;
    }
};

public void setData(Hvac havc){
    if (iRemoteService!=null){
        iRemoteService.setData(hvac);
    }
}

常規(guī)的用法中,我們需先判斷Client端是否已經綁定上Server端,不僅Client端對Server端的接口調用,也要防止綁定失敗導致的空指針。

車載應用中上述的常規(guī)用法不僅會使HMI開發(fā)變得繁瑣,還需要處理Service異常狀態(tài)下解除綁定后的狀態(tài)。下面介紹如何簡便的封裝SDK

封裝SDK Base類

實際開發(fā)中,我們把Client端對Service的綁定、重連、線程切換等細節(jié)隱藏到SDK中并封裝成一個BaseConnectManager,使用時只需要繼承BaseConnectManager并傳入Service的包名、類名和期望的斷線重連時間即可。

public abstract class BaseConnectManager<T extends IInterface> {

    private final String TAG = SdkLogUtils.TAG_FWK + getClass().getSimpleName();
    private static final String THREAD_NAME = "bindServiceThread";

    private final Application mApplication;
    private IServiceConnectListener mServiceListener;
    private final Handler mChildThread;
    private final Handler mMainThread;
    private final LinkedBlockingQueue<Runnable> mTaskQueue = new LinkedBlockingQueue<>();
    private final Runnable mBindServiceTask = this::bindService;
    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            SdkLogUtils.logV(TAG, "[onServiceConnected]");
            mProxy = asInterface(service);
            Remote.tryExec(() -> {
                service.linkToDeath(mDeathRecipient, 0);
            });
            if (mServiceListener != null) {
                mServiceListener.onServiceConnected();
            }
            handleTask();
            mChildThread.removeCallbacks(mBindServiceTask);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            SdkLogUtils.logV(TAG, "[onServiceDisconnected]");
            mProxy = null;
            if (mServiceListener != null) {
                mServiceListener.onServiceDisconnected();
            }
        }
    };

    private final IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
        @Override
        public void binderDied() {
            SdkLogUtils.logV(TAG, "[binderDied]");
            if (mServiceListener != null) {
                mServiceListener.onBinderDied();
            }

            if (mProxy != null) {
                mProxy.asBinder().unlinkToDeath(mDeathRecipient, 0);
                mProxy = null;
            }

            attemptToRebindService();
        }

    };

    private T mProxy;

    public BaseConnectManager() {
        mApplication = SdkAppGlobal.getApplication();
        HandlerThread thread = new HandlerThread(THREAD_NAME, 6);
        thread.start();
        mChildThread = new Handler(thread.getLooper());
        mMainThread = new Handler(Looper.getMainLooper());
        bindService();
    }

    private void bindService() {
        if (mProxy == null) {
            SdkLogUtils.logV(TAG, "[bindService] start");
            ComponentName name = new ComponentName(getServicePkgName(), getServiceClassName());
            Intent intent = new Intent();
            if (getServiceAction() != null) {
                intent.setAction(getServiceAction());
            }
            intent.setComponent(name);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                mApplication.startForegroundService(intent);
            } else {
                mApplication.startService(intent);
            }
            boolean connected = mApplication.bindService(intent, mServiceConnection,
                    Context.BIND_AUTO_CREATE);
            SdkLogUtils.logV(TAG, "[bindService] result " + connected);
            if (!connected) {
                attemptToRebindService();
            }
        } else {
            SdkLogUtils.logV(TAG, "[bindService] not need");
        }
    }

    protected void attemptToRebindService() {
        SdkLogUtils.logV(TAG, "[attemptToRebindService]");
        mChildThread.postDelayed(mBindServiceTask, getRetryBindTimeMill());
    }

    protected void handleTask() {
        Runnable task;
        while ((task = mTaskQueue.poll()) != null) {
            SdkLogUtils.logV(TAG, "[handleTask] poll task form task queue");
            mChildThread.post(task);
        }
    }

    public void init() {
        bindService();
    }

    public boolean isServiceConnected() {
        return isServiceConnected(false);
    }

    public boolean isServiceConnected(boolean tryConnect) {
        SdkLogUtils.logV(TAG, "[isServiceConnected] tryConnect " + tryConnect + ";isConnected " + (mProxy != null));
        if (mProxy == null && tryConnect) {
            attemptToRebindService();
        }
        return this.mProxy != null;
    }

    public void release() {
        SdkLogUtils.logV(TAG, "[release]");
        if (this.isServiceConnected()) {
            this.mProxy.asBinder().unlinkToDeath(this.mDeathRecipient, 0);
            this.mProxy = null;
            this.mApplication.unbindService(mServiceConnection);
        }
    }

    public void setStateListener(IServiceConnectListener listener) {
        SdkLogUtils.logV(TAG, "[setStateListener]" + listener);
        mServiceListener = listener;
    }

    public void removeStateListener() {
        SdkLogUtils.logV(TAG, "[removeStateListener]");
        mServiceListener = null;
    }

    protected T getProxy() {
        return mProxy;
    }

    protected LinkedBlockingQueue<Runnable> getTaskQueue() {
        return mTaskQueue;
    }

    public Handler getMainHandler() {
        return mMainThread;
    }

    protected abstract String getServicePkgName();

    protected abstract String getServiceClassName();

    protected String getServiceAction() {
        return null;
    }

    protected abstract T asInterface(IBinder service);

    protected abstract long getRetryBindTimeMill();

}

封裝 SDK

開發(fā)中多數時候我們只有一個用于操作Service Interface,如下所示:

interface HvacInterface {

    oneway void setTemperature(int temperature);

    oneway void requestTemperature();

    boolean registerCallback(in HvacCallback callback);

    boolean unregisterCallback(in HvacCallback callback);

}

用于回調Server端處理結果的Callback

interface HvacCallback {

    oneway void onTemperatureChanged(double temperature);

}

基于BaseConnectManager封裝一個HvacManager

public class HvacManager extends BaseConnectManager<HvacInterface> {

    private static final String TAG = SdkLogUtils.TAG_FWK + HvacManager.class.getSimpleName();

    private static volatile HvacManager sHvacManager;

    public static final String SERVICE_PACKAGE = "com.fwk.service";
    public static final String SERVICE_CLASSNAME = "com.fwk.service.SimpleService";
    private static final long RETRY_TIME = 5000L;

    private final List<IHvacCallback> mCallbacks = new ArrayList<>();

    private final HvacCallback.Stub mSampleCallback = new HvacCallback.Stub() {
        @Override
        public void onTemperatureChanged(double temperature) throws RemoteException {
            SdkLogUtils.logV(TAG, "[onTemperatureChanged] " + temperature);
            getMainHandler().post(() -> {
                for (IHvacCallback callback : mCallbacks) {
                    callback.onTemperatureChanged(temperature);
                }
            });
        }
    };

    public static HvacManager getInstance() {
        if (sHvacManager == null) {
            synchronized (HvacManager.class) {
                if (sHvacManager == null) {
                    sHvacManager = new HvacManager();
                }
            }
        }
        return sHvacManager;
    }

    @Override
    protected String getServicePkgName() {
        return SERVICE_PACKAGE;
    }

    @Override
    protected String getServiceClassName() {
        return SERVICE_CLASSNAME;
    }

    @Override
    protected HvacInterface asInterface(IBinder service) {
        return HvacInterface.Stub.asInterface(service);
    }

    @Override
    protected long getRetryBindTimeMill() {
        return RETRY_TIME;
    }

    /******************/
  
    public void requestTemperature() {
        Remote.tryExec(() -> {
            if (isServiceConnected(true)) {
                getProxy().requestTemperature();
            } else {
                // 將此方法放入隊列中,等Service重新連接后,會依次調用
                getTaskQueue().offer(this::requestTemperature);
            }
        });
    }

    public void setTemperature(int temperature) {
        Remote.tryExec(() -> {
            if (isServiceConnected(true)) {
                getProxy().requestTemperature();
            } else {
                getTaskQueue().offer(() -> {
                    setTemperature(temperature);
                });
            }
        });
    }

    public boolean registerCallback(IHvacCallback callback) {
        return Remote.exec(() -> {
            if (isServiceConnected(true)) {
                boolean result = getProxy().registerCallback(mSampleCallback);
                if (result) {
                    mCallbacks.remove(callback);
                    mCallbacks.add(callback);
                }
                return result;
            } else {
                getTaskQueue().offer(() -> {
                    registerCallback(callback);
                });
                return false;
            }
        });
    }

    public boolean unregisterCallback(IHvacCallback callback) {
        return Remote.exec(() -> {
            if (isServiceConnected(true)) {
                boolean result = getProxy().unregisterCallback(mSampleCallback);
                if (result) {
                    mCallbacks.remove(callback);
                }
                return result;
            } else {
                getTaskQueue().offer(() -> {
                    unregisterCallback(callback);
                });
                return false;
            }
        });
    }
}

上述代碼中,我們需要注意一點,每次調用遠程方法都需要判斷當前service是否處于連接,如果與Service的連接被斷開了,我們要把方法放入一個隊列中去,當Service重新被綁定上后,隊列中的方法,會依次被取出執(zhí)行。

最后,我們在SDK module的 build.gradle中加入可以編譯出jar的腳本

// makeJar
def zipFile = file('build/intermediates/aar_main_jar/release/classes.jar')
task makeJar(type: Jar) {
    from zipTree(zipFile)
    archiveBaseName =  "sdk"
    destinationDirectory = file("build/outputs/")
    manifest {
        attributes(
                'Implementation-Title': "${project.name}",
                'Built-Date': new Date().getDateTimeString(),
                'Built-With':
                        "gradle-${project.getGradle().getGradleVersion()},groovy-${GroovySystem.getVersion()}",
                'Created-By':
                        'Java ' + System.getProperty('java.version') + ' (' + System.getProperty('java.vendor') + ')')
    }
}
makeJar.dependsOn(build)

使用示例

public void requestTemperature() {
    LogUtils.logI(TAG, "[requestTemperature]");
    HvacManager.getInstance().requestTemperature();
}

實際使用時,調用方既不需要關心Service的綁定狀態(tài),也不需要主動進行線程切換,極大的簡便了HMI的開發(fā)。
本文源碼地址: https://github.com/linux-link/CarServerArch

參考資料

Android 接口定義語言 (AIDL) | Android 開發(fā)者 | Android Developers

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容