AIDL實現跨進程通信

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


 
  1. interface MyAidlService {

  2. int plus(int a, int b);

  3. }

 

2. MyService.java


 
  1. public class MyService extends Service{

  2.  
  3. MyAidlService.Stub mBinder = new MyAidlService.Stub() {

  4. @Override

  5. public int plus(int a, int b) throws RemoteException {

  6. return a + b;

  7. }

  8. };

  9.  
  10. @Override

  11. public IBinder onBind(Intent intent) {

  12. return mBinder;

  13. }

  14.  
  15. @Override

  16. public void onCreate() {

  17. super.onCreate();

  18. }

  19.  
  20. @Override

  21. public void onDestroy() {

  22. super.onDestroy();

  23. }

  24.  
  25. @Override

  26. public int onStartCommand(Intent intent, int flags, int startId) {

  27. return super.onStartCommand(intent, flags, startId);

  28. }

  29.  
  30.  
  31. }


3.添加action


 
  1. <service android:name=".MyService">

  2. <intent-filter>

  3. <action android:name="com.liu.servicetest.MyAidlService"/>

  4. </intent-filter>

  5. </service>


4.拷貝AIDL文件夾
5.A訪問B的服務


 
  1. Intent intent = new Intent("com.liu.servicetest.MyAidlService");

  2. bindService(intent, connection, BIND_AUTO_CREATE);

 

private MyAidlService aidlService;

 
  1. private ServiceConnection connection = new ServiceConnection() {

  2. @Override

  3. public void onServiceConnected(ComponentName name, IBinder service) {

  4. Log.d("onServiceConnected", "jinlaile");

  5. aidlService = (MyAidlService) MyAidlService.Stub.asInterface(service);

  6. try {

  7. int plus = aidlService.plus(100, 50);//對100和50相加

  8. Log.d("onServiceConnected", plus + "");

  9. } catch (RemoteException e) {

  10. e.printStackTrace();

  11. }

  12. }

  13.  
  14.  
  15. @Override

  16. public void onServiceDisconnected(ComponentName name) {

  17.  
  18.  
  19. }

  20. };

 

 

這就是整個流程

看結果:

剛好是150!

注意:
AS和Eclipse建立AIDL文件的方法不一樣,詳情請看Android Stdio建立AIDL文件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章