個人理解的通信原理就是客戶端和服務端使用同一個接口,服務端通過service實現這個接口的方法并且暴露(注冊),客戶端通過與service連接得到接口關聯,之后客戶端就能調用服務端接口的方法了(粗略理解,個人覺得每次接口改變,客戶端和服務端都得改,這種架構并不好)
需要注意幾點:
1.編寫.aidl文件,IDE會自動再gen目錄生成.java文件(客戶端和服務端都一樣,且.aidl文件要保持一致)
2.服務端要寫service,重寫onBind方法,返回.aidl的Stub,Stub要實現.aidl的方法,如下例子:
@Override public IBinder onBind(Intent intent) { return new IAdditionService.Stub() { /* * Implement com.android.hellosumaidl.IAdditionService.add(int, int) */ @Override public int add(int value1, int value2) throws RemoteException { return value1 + value2; } }; }3.客戶端調用的service的action要與服務端注冊的service的name保持一致4.客戶端通過ServiceConnection得到服務端的接口,并且使用bindService來調用,如下:
class AdditionServiceConnection implements ServiceConnection { public void onServiceConnected(ComponentName name, IBinder boundService) { service = IAdditionService.Stub.asInterface((IBinder)boundService); Toast.makeText(MainActivity.this, "Service connected", Toast.LENGTH_LONG).show(); } public void onServiceDisconnected(ComponentName name) { service = null; Toast.makeText(MainActivity.this, "Service disconnected", Toast.LENGTH_LONG).show(); } } PRivate void initService() { connection = new AdditionServiceConnection(); Bundle args = new Bundle(); Intent intent = new Intent("test.aidl.AdditionService"); intent.putExtras(args); bindService(intent,connection,Context.BIND_AUTO_CREATE); }demo下載地址:http://download.csdn.net/detail/shuaicike/9749061
新聞熱點
疑難解答