還在用AIDL嗎?試試EasyMessenger吧

EasyMessenger

直達Github項目地址java

一款用於Android平臺的基於Binder的進程間通訊庫,採用annotationProcessor生成IPC通訊須要的代碼。EasyMessenger相對於AIDL具有以下優點:git

  • 採用Java聲明接口,更方便
  • 接口方法支持重載
  • 同時支持同步和異步通訊

EasyMessenger目前支持以下數據類型:github

  • 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通訊。ide

//使用以前須要初始化
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

實現接口:ui

@BinderServer
public class FunctionImpl
{
    //必須是pubic
    //方法名稱、參數數量、類型、順序必須和client的接口一致
    public int add(int num1, int num2)
    {
        
    }
}

build以後會生成FunctionImplBinder,將這個Binder和Service綁定:code

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

直達Github項目地址server

歡迎關注個人博客接口

相關文章
相關標籤/搜索