還在用AIDL嗎?試試EasyMessenger吧

程式碼超人發表於2019-02-21

EasyMessenger

直達Github專案地址

一款用於Android平臺的基於Binder的程式間通訊庫,採用annotationProcessor生成IPC通訊需要的程式碼。EasyMessenger相對於AIDL具備如下優勢:

  • 採用Java宣告介面,更方便
  • 介面方法支援過載
  • 同時支援同步和非同步通訊

EasyMessenger目前支援如下資料型別:

  • boolean, byte, char, short, int, long, float, double
  • boolean[], byte[], char[], int[], long[], float[], double[]
  • String, String[]
  • Parcelable, Parcelable[]
  • Serializable
  • ArrayList
  • enum(需要實現parcelable)

下載

implementation 'cn.zmy:easymessenger-lib:0.1'
annotationProcessor 'cn.zmy:easymessenger-compilier:0.1'
複製程式碼

開始使用

Client

宣告介面:

@BinderClient
public interface ClientInterface
{
    int add(int num1, int num2);
}
複製程式碼

build之後,會生成ClientInterfaceHelper類,開發者也正是通過這個Helper類進行IPC通訊。

//使用之前需要初始化
ClientInterfaceHelper.instance.__init(context, 
    new ComponentName("{server_package}", "{server_service_name}"));
    
//同步IPC呼叫
int result = ClientInterfaceHelper.instance.add(1, 2);
    
//非同步IPC呼叫
ClientInterfaceHelper.instance.addAsync(1, 2, new IntCallback()
{
    @Override
    public void onSuccess(int result)
    {
        //呼叫成功
    }

    @Override
    public void onError(Exception ex)
    {
        //呼叫失敗
    }
});
複製程式碼

Server

實現介面:

@BinderServer
public class FunctionImpl
{
    //必須是pubic
    //方法名稱、引數數量、型別、順序必須和client的介面一致
    public int add(int num1, int num2)
    {
        
    }
}
複製程式碼

build之後會生成FunctionImplBinder,將這個Binder和Service繫結:

public class ServerService extends Service
{
    @Override
    public IBinder onBind(Intent intent)
    {
        return new FunctionImplBinder(new FunctionImpl());
    }
}
複製程式碼

直達Github專案地址

歡迎關注我的部落格

相關文章