Android 進程間通信binder使用心得

分類:技術 時間:2017-01-20

在android5.0之後不再支持隱式意圖開啟service,需指明service所在app的包名和類名全路徑。

以下是應用A,開啟應用B中service的偽代碼:

Intent intent = new Intent();
//ComponentName中第一個參數為app的包名,第二個為service的完整類名
//從下面代碼可知MyServiceDemo在包名為cn.com.focus.testproject應用下,
//其完整類名路徑cn.com.focus.testproject.abc.MyServiceDemo
intent.setComponent(new ComponentName("cn.com.focus.testproject","cn.com.focus.testproject.abc.MyServiceDemo"));
startService(intent);
//開啟service後還可以綁定servcie。
bindService(intent, new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
	    獲取到的接口對象(這塊不太了解的可以先學習下aidl)
            iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
            Log.d(TAG, "onServiceConnected() called with: name = [" + name + "], service = [" + service + "]");
            
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "onServiceDisconnected() called with: name = [" + name + "]");
        }
    }, Context.BIND_AUTO_CREATE);
}

我們拿到IMyAidlInterface的接口對象後可以調用內部聲明的方法了,這裏需要重點說明一下這些方法的運行環境,
1、我們client調用方調用server的方法是同步的會等接口的返回值;所以如果所掉的方法是一個耗時任務我們應該放在
線程中調用避免ANR異常。
2、server內部的方法是運行在一個新的線程中的,這樣就保證了我們server支持異步操作和支持多client同時調用。


Tags: android

文章來源:


ads
ads

相關文章
ads

相關文章

ad