1. 程式人生 > >AIDL 程序間通訊講解及實現步驟

AIDL 程序間通訊講解及實現步驟

server端的實現

1.建立 aidl檔案 (例如ICatl.aidl)

2。建立一個server 並在server中建立一個內部類,繼承aidl檔案的stub例如:
public class AidlService extends Service {
  
    private CatBinder catBinder;  
    //此處要繼承Stub,實現ICat和IBinder介面  
   public class CatBinder extends ICat.Stub
    {  
        @Override  
        public String getColor() throws RemoteException {
//這裡做一些操作,獲得客戶端想要的資料,例如查詢資料庫
             return "red";

        }  
  
        @Override  
        public double getWeight() throws RemoteException {  
            return 9.9;  
        }  
    }
  
    @Override  
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this,"oncreat",Toast.LENGTH_SHORT).show();
        catBinder = new CatBinder();
    }
  
    @Override  
    public IBinder onBind(Intent intent) {
        return catBinder;
    }  
  
    @Override  
    public void onDestroy() {  
        System.out.println("remote service destroy");  
    }  
}

注意:
如果是eclipse需要在src目錄和ICat.aidl相同的包名下建立 Icat.java檔案
如果是android studio編譯器不用建立 ICat.java 編譯器會自動建立注意使用aidl的server 一定要和aidl檔案有相同的包名

client端的實現

1.將服務類的aidl檔案拷貝過來 (注意:和service端的aidl一定在一個包名下面)2.需要從服務端獲得資料時,繫結服務
Intent intent = new Intent();
intent.setAction("AidlService");
intent.setPackage(包名);
bindService(intent,conn, Service.BIND_AUTO_CREATE)

bind服務成功後回撥ServiceConnection的onServiceConnected方法,

    ServiceConnection conn =new ServiceConnection(){

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Toast.makeText(MainActivity.this,"connected",Toast.LENGTH_SHORT).show();
            mICat = ICat.Stub.asInterface(service);
            try {
             String   color = mICat.getColor();
            } catch (RemoteException e) {
                e.printStackTrace();
            }

        }