2014年3月20日 星期四

Android 開發 (三十三) 遠端 Service AIDL 的使用

假設今天有兩個app要互相傳遞資料

例如

我有兩個書本定閱app ,這兩個app的書單必須同步,要如何做到?

可以使用AIDL(Android Interface Definition Language),這可以讓我們同時access同一個service,
所以接下來我想做的事情是
1. 建立兩支app存取的interface 以及model
2. 建立 兩支app
3. 建立 一個service


首先必須先建立interface,這邊可以使用android內建的方法,我們只需要創建好.aidl檔之後
android會幫我們建好.java檔,


可以看到在上圖的interface裡面,我有使用自己建立的Book , aidl 可以import 繼承自parceable的物件,不過繼承的物件也必須有自己的aidl檔
如下圖 book.aidl


接著我們必須建立兩支app ,然後使用bindservice將interface取回

  conn = new MyServiceConnection();
  bindService(intent, conn, Context.BIND_AUTO_CREATE);

在ServiceConnection中我們可以使用 asInterface將我們需要的interface 取回

 class MyServiceConnection implements ServiceConnection{

  @Override
  public void onServiceConnected(ComponentName name, IBinder service) {
   manager = BookListManager.Stub.asInterface(service);
   
  }

  @Override
  public void onServiceDisconnected(ComponentName name) {
   manager = null;
   
  }
  
 }

在取得interface之後,我們就可以使用相關的method


在建立好兩支app之後,接著就只需將Service建立完成即可
如下圖在binder裡將interface.stub回傳回去,使mainactivity可以取得service的interface



這樣就完成了,只需要在一開始startservice之後就可以共享資料了。

在這邊必須注意一點,
就是兩個app的aidl檔必須完全一致,包含package name
如下圖

否則會出現
SecurityException: Binder invocation to an incorrect interface 這個錯誤

接著附上sampleCode

沒有留言:

張貼留言