AIDL是Android接口定義語言的意思,它可以用於讓某個Service與多個應用程序組件之間進行跨進程通信,從而可以實現多個應用程序共享同一個Service的功能。
首先先寫具體的步驟:
### 實現方法 ###
例:用 A程序去訪問 B程序的MyService.java服務
1. 在B中建立AIDL文件MyAidlService.AIDL,在AIDL文件裏寫我們的接口方法
2. 在MyService中寫AIDL文件定義的方法的具體服務邏輯
3. 在B的manifest文件中,爲Service添加action "com.liu.servicetest.MyAidlService" 用於A靜態來訪問Service
(這裏是因爲,如果用動態Intent (this, MyService.class), 在A中沒有MyService這個類)
4. 把B的AIDL文件夾拷貝到A中,一定要注意包的路徑依然爲B中的路徑
5.在A中利用靜態Intent來啓動B的服務MyService
對應步驟詳細代碼:
1. MyAidlService.AIDL
-
interface MyAidlService {
-
int plus(int a, int b);
-
}
2. MyService.java
-
public class MyService extends Service{
-
MyAidlService.Stub mBinder = new MyAidlService.Stub() {
-
@Override
-
public int plus(int a, int b) throws RemoteException {
-
return a + b;
-
}
-
};
-
@Override
-
public IBinder onBind(Intent intent) {
-
return mBinder;
-
}
-
@Override
-
public void onCreate() {
-
super.onCreate();
-
}
-
@Override
-
public void onDestroy() {
-
super.onDestroy();
-
}
-
@Override
-
public int onStartCommand(Intent intent, int flags, int startId) {
-
return super.onStartCommand(intent, flags, startId);
-
}
-
}
3.添加action
-
<service android:name=".MyService">
-
<intent-filter>
-
<action android:name="com.liu.servicetest.MyAidlService"/>
-
</intent-filter>
-
</service>
4.拷貝AIDL文件夾
5.A訪問B的服務
-
Intent intent = new Intent("com.liu.servicetest.MyAidlService");
-
bindService(intent, connection, BIND_AUTO_CREATE);
private MyAidlService aidlService;
-
private ServiceConnection connection = new ServiceConnection() {
-
@Override
-
public void onServiceConnected(ComponentName name, IBinder service) {
-
Log.d("onServiceConnected", "jinlaile");
-
aidlService = (MyAidlService) MyAidlService.Stub.asInterface(service);
-
try {
-
int plus = aidlService.plus(100, 50);//對100和50相加
-
Log.d("onServiceConnected", plus + "");
-
} catch (RemoteException e) {
-
e.printStackTrace();
-
}
-
}
-
@Override
-
public void onServiceDisconnected(ComponentName name) {
-
}
-
};
這就是整個流程
看結果:
剛好是150!
注意:
AS和Eclipse建立AIDL文件的方法不一樣,詳情請看Android Stdio建立AIDL文件