溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Android AIDL實(shí)現(xiàn)跨進(jìn)程通信的示例代碼

發(fā)布時間:2020-08-30 21:03:52 來源:腳本之家 閱讀:261 作者:xybCoder博客 欄目:移動開發(fā)

AIDL是Android接口定義語言,它可以用于讓某個Service與多個應(yīng)用程序組件之間進(jìn)行跨進(jìn)程通信,從而可以實(shí)現(xiàn)多個應(yīng)用程序共享同一個Service的功能。

實(shí)現(xiàn)步驟

例:用 A程序去訪問 B程序的MyService.java服務(wù)

  1. 在B中建立AIDL文件MyAidlService.AIDL,在AIDL文件里寫我們的接口方法
  2. 在MyService中寫AIDL文件定義的方法的具體服務(wù)邏輯
  3. 在B的manifest文件中,為Service添加action “com.xyb.servicetest.MyAidlService” 用于A靜態(tài)來訪問Service(這里是因?yàn)?,如果用動態(tài)Intent (this, MyService.class), 在A中沒有MyService這個類)
  4. 把B的AIDL文件夾拷貝到A中,一定要注意包的路徑依然為B中的路徑
  5. 在A中利用靜態(tài)Intent來啟動B的服務(wù)MyService

對應(yīng)步驟詳細(xì)代碼:

MyAidlService.AIDL

interface MyAidlService { 
  int add(int a, int b); 
}

MyService.Java

public class MyService extends Service{ 
 
  MyAidlService.Stub mBinder = new MyAidlService.Stub() { 
    @Override 
    public int add(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.xyb.servicetest.MyAidlService"/> 
      </intent-filter> 
    </service>

4.拷貝AIDL文件夾

5.A訪問B的服務(wù)

Intent intent = new Intent("com.xyb.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", "onServiceConnected"); 
    aidlService = (MyAidlService) MyAidlService.Stub.asInterface(service); 
    try { 
      int sum = aidlService.add(10, 50);//對10和50相加 
      Log.d("onServiceConnected", sum + ""); 
    } catch (RemoteException e) { 
      e.printStackTrace(); 
    } 
  } 
 
 
  @Override 
  public void onServiceDisconnected(ComponentName name) { 
 
 
  } 
};

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI