最近公司需要開發一個項目用的到aidl,之前研究過eclipse版本的,但是好久了一直沒用,現在需要撿起來,但是現在都用android studio了,所以查了下資料 都不是很全,我在這里總結一下,方便后續忘了在用到。
第一步:通過as創建一個aidl文件,在app右鍵,如下圖:

輸入自己想要的名字,別的都默認,點擊Finish 我這里的名字叫 PayAidlInterface 創建好如下:

在看看 PayAidlInterface.aidl 里面怎么寫的,其實就一個計算的方法 客戶端傳2個int類型的值,服務端計算和
// PayAidlInterface.aidl package com.txy.umpay.aidl; // Declare any non-default types here with import statements interface PayAidlInterface { /** * Demonstrates some basic types that you can use as parameters * and return values in AIDL. */ int calculation(int anInt, int bnInt); }
第二步: PayAidlInterface.aidl 編寫完成之后 需要Build-->Make Module app,生成相應的java文件,如下圖:

在來看看生成的java文件的位置:

第三步:接下來,就該完成我們的MAIDLService邏輯部分了,MAIDLService.java代碼如下:
先說下我遇到的坑,我是通過as右鍵創建的service 他自動會加上下面2個屬性 就會導致客戶端調用不起來,所以記得一定要刪除
android:enabled="false"
android:exported="false"、
public class MAIDLService extends Service { private void Log(String str) { Log.e("123", "----------" + str + "----------"); } public void onCreate() { Log("service created"); } public void onStart(Intent intent, int startId) { Log("service started id = " + startId); } public IBinder onBind(Intent t) { Log("service on bind"); return mBinder; } public void onDestroy() { Log("service on destroy"); super.onDestroy(); } public boolean onUnbind(Intent intent) { Log("service on unbind"); return super.onUnbind(intent); } public void onRebind(Intent intent) { Log("service on rebind"); super.onRebind(intent); } PayAidlInterface.Stub mBinder = new PayAidlInterface.Stub() { @Override public int calculation(int anInt, int bnInt) throws RemoteException { Log(anInt + "--" + bnInt); return 1; } }; }
在來看下AndroidManifest.xml中MAIDLService 的配置:action是客戶端調用用到的
<service android:name=".MAIDLService">
<intent-filter>
<action android:name="com.txy.umpay.aidl.MAIDLService" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
服務端就已經完成了。接下來我們來看一下客戶端的:
同樣可以需要可服務端一樣創建aidl文件

其實和服務端是一樣的,把服務端的 PayAidlInterface.aidl 文件復制過來 再次執行 Build-->Make Module app
在來看下客戶端怎么調用的
第一步先創建一個ServiceConnection 對象:
private ServiceConnection mServiceConnection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName arg0) { Log.e("123", "onServiceDisconnected:" + arg0.getPackageName()); } @Override public void onServiceConnected(ComponentName name, IBinder binder) { Log.e("123", "onServiceConnected:" + name.getPackageName()); // 獲取遠程Service的onBinder方法返回的對象代理 service = PayAidlInterface.Stub.asInterface(binder); } };
第二步綁定:
//使用意圖對象綁定開啟服務 Intent intent = new Intent(); //在5.0及以上版本必須要加上這個 intent.setPackage("com.txy.umpay.aidl"); intent.setAction("com.txy.umpay.aidl.MAIDLService");//這個是上面service的action bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
第三步調用:
if(service != null){ int calculation = service.calculation(1, 2); text.setText("calculation:"+calculation); }
第四部不用的時候解除綁定:
@Override protected void onDestroy () { super.onDestroy(); if (mServiceConnection != null) { unbindService(mServiceConnection); } }
