1. 程式人生 > 程式設計 >詳解Android aidl的使用方法

詳解Android aidl的使用方法

AIDL是Android中IPC(Inter-Process Communication)方式中的一種,AIDL是Android Interface definition language的縮寫(對於小白來說,AIDL的作用是讓你可以在自己的APP裡繫結一個其他APP的service,這樣你的APP可以和其他APP互動。)

AIDL只是Android中眾多程序間通訊方式中的一種方式,

AIDL和Messenger的區別:

  1. Messenger不適用大量併發的請求:Messenger以序列的方式來處理客戶端發來的訊息,如果大量的訊息同時傳送到服務端,服務端仍然只能一個個的去處理。
  2. Messenger主要是為了傳遞訊息:對於需要跨程序呼叫服務端的方法,這種情景不適用Messenger。
  3. Messenger的底層實現是AIDL,系統為我們做了封裝從而方便上層的呼叫。
  4. AIDL適用於大量併發的請求,以及涉及到服務端端方法呼叫的情況

AIDL通訊的原理:首先看這個檔案有一個叫做proxy的類,這是一個代理類,這個類執行在客戶端中,其實AIDL實現的程序間的通訊並不是直接的通訊,客戶端和服務端都是通過proxy來進行通訊的:客戶端呼叫的方法實際是呼叫是proxy中的方法,然後proxy通過和服務端通訊將返回的結果返回給客戶端。

1、AIDL的作用

AIDL是用於Android的IPC通訊的,因此可以在一個APP內部通訊,也可以建立兩個APP之間進行通訊。

AIDL的職能分配很明確,Service作為後臺執行作為伺服器管理各種互動,Client作為客戶端請求資料或呼叫Service的方法。

2、AIDL的簡單使用

1)建立一個aidl檔案,直接右鍵建立就可以了,

package com.example.mytest;

// IMyAidlInterface.aidl
package com.example.mytest;
 
// Declare any non-default types here with import statements
 
interface IMyAidlInterface {
  /**
   * Demonstrates some basic types that you can use as parameters
   * and return values in AIDL.
   */
  void basicTypes(int anInt,long aLong,boolean aBoolean,float aFloat,double aDouble,String aString);
  String add(int x,int y);
}

2)選中剛剛建立的 .aidl檔案 生產對應的java檔案。

AndroidStudio 可以通過Build--》model App 完成

3)編寫Service的具體物件 實現介面

package com.example.mytest;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
public class FirstService extends Service {
  public FirstService() {
  }
  private static String Tag = "FirstService";
  @Override
  public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    //throw new UnsupportedOperationException("Not yet implemented");
    Log.d(Tag,"service on bind");
    return mBinder;
  }
  @Override
  public void onCreate() {
    super.onCreate();
    Log.d(Tag,"OnCreate");
  }
  @Override
  public int onStartCommand(Intent intent,int flags,int startId) {
    Log.d(Tag,"onStartCommand");
    return START_STICKY;
  }
  @Override
  public boolean onUnbind(Intent intent) {
    Log.d(Tag,"onUnbind");
    return super.onUnbind(intent);
  }
  @Override
  public void onDestroy() {
    super.onDestroy();
    Log.d(Tag,"onDestroy");
  }
  IMyAidlInterface.Stub mBinder = new IMyAidlInterface.Stub(){
    @Override
    public void basicTypes(int anInt,String aString) throws RemoteException {
    }
    @Override
    public String add(int x,int y) throws RemoteException {
      Log.d(Tag,x + "--" + y);
      return String.valueOf(x + y);
    }
  };
}

注意:onBund 返回IBinder型別,為了後面的回撥會調動

4)確定一下AndroidManifest.xml裡面的Service內容

 <service
      android:name=".FirstService"
      android:enabled="true"
      android:exported="true">
      <intent-filter>
        <action android:name="com.example.mytest.aidl.FirstService"/>
      </intent-filter>
 
    </service>

5)開啟服務

 private Button btnStartService; 
  private Button btnBindService;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
 
    initView();
  }
 
  private void initView() {
    tvId = (TextView) findViewById(R.id.tv_id);
 
    btnStartService = (Button) findViewById(R.id.btn_Start_Service);
    btnStartService.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        Intent intent = new Intent();
        intent.setPackage("com.example.mytest");
        intent.setAction("com.example.mytest.aidl.FirstService");
        startService(intent);
      }
    });
 
    btnBindService = (Button) findViewById(R.id.btnBindService);
    btnBindService.setOnClickListener(new View.OnClickListener() {
      @Override
        public void onClick(View view) {
            bind();
        }
    });
  
 
  private void bind(){
    Log.d(Tag,"bind");
    Intent intent = new Intent();
    intent.setPackage("com.example.mytest");
    if(controllerConnection != null){
      this.bindService(intent,controllerConnection,this.BIND_AUTO_CREATE);//繫結服務,建立連結
    }
    else {
      Log.d(Tag,"controllerConnection != null");
    }
  }
 
  private void unbind(){
    if(controllerConnection != null && myAIDLController.asBinder().isBinderAlive()){
      try{
        Log.d(Tag,"this.unbindService(controllerConnection);");
        this.unbindService(controllerConnection);
      } catch (Exception localException) {
        Log.w(Tag,"unbind Exception localException");
      }
    }
  }

在bind的時候是非同步的,因此可以通過onServiceConnected()來判斷繫結上後的操作。

private ServiceConnection controllerConnection = new ServiceConnection(){
 
    @Override
    public void onServiceConnected(ComponentName componentName,IBinder iBinder) {
      Log.d(Tag,"onServiceConnected");
 
      myAIDLController = IMyAidlInterface.Stub.asInterface(iBinder);
      if (myAIDLController != null) {
        try {
          Log.d(Tag,"ServiceConnection success");
          Toast.makeText(MainActivity.this,"ServiceConnection success",Toast.LENGTH_LONG).show();
        } catch (Exception localException) {
          Log.w(Tag,"Exception localException");
        }
      }
    }
 
    @Override
    public void onServiceDisconnected(ComponentName componentName) {
      Log.d(Tag,"onServiceDisconnected");
      Toast.makeText(MainActivity.this,"onServiceDisconnected",Toast.LENGTH_LONG).show();
 
      myAIDLController = null;
    }
 
    @Override
    public void onBindingDied(ComponentName name) {
      Log.d(Tag,"onBindingDied");
    }
 
    @Override
    public void onNullBinding(ComponentName name) {
      Log.d(Tag,"onNullBinding");
    }
  };

6)呼叫Service方法add()

呼叫的時候需要繫結Service方法,上面已經有了,接下來呼叫就簡單了,建立一個Button,然後拿到Service的控制物件,呼叫方法add

 btnServiceFunc = (Button) findViewById(R.id.btnServiceFunc);
    btnServiceFunc.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        try {
          Log.d(Tag,String.valueOf( myAIDLController.add(1,2)));
        } catch (RemoteException e) {
          e.printStackTrace();
        }
      }
    });

到此這篇關於詳解Android aidl的使用方法的文章就介紹到這了,更多相關Android aidl的使用內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!