Flutter與android之間的通訊

白瑞德發表於2019-08-12

Platform Channel簡介

Flutter引入Platform Channel機制來支援不同平臺的API呼叫。在Flutter中,提供了三種Platform Channel用來支援和平臺之間資料的傳遞:

  • BasicMessageChannel:支援字串和半結構化的資料傳遞,可以通過BasicMessageChannel來獲取Native專案的圖示等資源
  • MethodChannel:支援傳遞方法呼叫,Flutter主動呼叫Native的方法,並獲取相應的返回值。既可以從Flutter發平臺發起方法呼叫,也可以從平臺程式碼向Flutter發起呼叫
  • EventChannel:支援資料流通訊,傳遞事件。收到訊息後無法回覆此次訊息,通常用於Native向Dart的通訊

使用方法

BasicMessageChannel

Android端:

BasicMessageChannel mBasicMessageChannel = new BasicMessageChannel(getFlutterView(), "basic_channel", StringCodec.INSTANCE);
mBasicMessageChannel.setMessageHandler(new BasicMessageChannel.MessageHandler() {
    //接受訊息
    @Override
    public void onMessage(Object o, BasicMessageChannel.Reply reply) {
        Log.e("basic_channel", "接收到來自flutter的訊息:"+o.toString());
        reply.reply("回饋訊息");
    }
});
//傳送訊息
mBasicMessageChannel.send("向flutter傳送訊息");
//傳送訊息並接受flutter的回饋
mBasicMessageChannel.send("向flutter傳送訊息", new BasicMessageChannel.Reply() {
            @Override
            public void reply(Object o) {
                
            }
});
複製程式碼

Flutter端:

const basicMessageChannel = const BasicMessageChannel('basic_channel', StringCodec());
//接受並回復訊息
basicMessageChannel.setMessageHandler(
      (String message) => Future<String>(() {
            setState(() {
              this.message = message;
            });
            return "回覆native訊息";
      }),
);
//傳送訊息
basicMessageChannel.send("來自flutter的message");
//flutter並沒有傳送並接受回覆訊息的`send(T message, BasicMessageChannel.Reply<T> callback)`方法
複製程式碼

MethodChannel

Android端:

MethodChannel mMethodChannel = new MethodChannel(getFlutterView(), "method_channel");
mMethodChannel.setMethodCallHandler(new MethodChannel.MethodCallHandler() {
    //響應flutter端的呼叫
    @Override
    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
        if (methodCall.method.equals("noticeNative")) {
            todo()
            result.success("接受成功");
        }
    }
});
//原生呼叫flutter
mMethodChannel.invokeMethod("noticeFlutter", "argument", new MethodChannel.Result() {
            @Override
            public void success(Object o) {
                //回撥成功
            }
            @Override
            public void error(String s,String s1, Object o) {
                //回撥失敗
            }
            @Override
            public void notImplemented() {

            }
});
複製程式碼

Flutter端:

const methodChannel = const MethodChannel('method_channel');
Future<Null> getMessageFromNative() async {
    //flutter調原生方法
    try {
      //回撥成功
      final String result = await methodChannel.invokeMethod('noticeNative');
      setState(() {
        method = result;
      });
    } on PlatformException catch (e) {
      //回撥失敗
    }
  }
methodChannel.setMethodCallHandler(
      (MethodCall methodCall) => Future<String>(() {
            //響應原生的呼叫
          if(methodCall.method == "noticeFlutter"){
            setState(() {
              
            });
          }
      }),
); 
複製程式碼

EventChannel

Android端:

EventChannel eventChannel = new EventChannel(getFlutterView(),"event_channel");
eventChannel.setStreamHandler(new EventChannel.StreamHandler() {
    @Override
    public void onListen(Object o, EventChannel.EventSink eventSink) {
        eventSink.success("成功");
        //eventSink.error("失敗","失敗","失敗");
    }
    @Override
    public void onCancel(Object o) {
        //取消監聽時呼叫
    }
});
複製程式碼

Flutter端:

const eventChannel = const EventChannel('event_channel');
eventChannel.receiveBroadcastStream().listen(_onEvent,onError:_onError);
void _onEvent(Object event) {
    //返回的內容
}
void _onError(Object error) {
    //返回的回撥
}
複製程式碼

其中:Object args是傳遞的引數,EventChannel.EventSink eventSink是Native回撥Dart時的會回撥函式,eventSink提供success、error與endOfStream三個回撥方法分別對應事件的不同狀態

原始碼初探

Platform Channel基本結構

首先了解一下這三種Channel的程式碼:

BasicMessageChannel
class BasicMessageChannel<T> {
  const BasicMessageChannel(this.name, this.codec);
  final String name;
  final MessageCodec<T> codec;
  Future<T> send(T message) async {
    return codec.decodeMessage(await BinaryMessages.send(name, codec.encodeMessage(message)));
  }
  void setMessageHandler(Future<T> handler(T message)) {
    if (handler == null) {
      BinaryMessages.setMessageHandler(name, null);
    } else {
      BinaryMessages.setMessageHandler(name, (ByteData message) async {
        return codec.encodeMessage(await handler(codec.decodeMessage(message)));
      });
    }
  }
  void setMockMessageHandler(Future<T> handler(T message)) {
    if (handler == null) {
      BinaryMessages.setMockMessageHandler(name, null);
    } else {
      BinaryMessages.setMockMessageHandler(name, (ByteData message) async {
        return codec.encodeMessage(await handler(codec.decodeMessage(message)));
      });
    }
  }
}
複製程式碼
MethodChannel
class MethodChannel {
  const MethodChannel(this.name, [this.codec = const StandardMethodCodec()]);
  final String name;
  final MethodCodec codec;
  void setMethodCallHandler(Future<dynamic> handler(MethodCall call)) {
    BinaryMessages.setMessageHandler(
      name,
      handler == null ? null : (ByteData message) => _handleAsMethodCall(message, handler),
    );
  }
  void setMockMethodCallHandler(Future<dynamic> handler(MethodCall call)) {
    BinaryMessages.setMockMessageHandler(
      name,
      handler == null ? null : (ByteData message) => _handleAsMethodCall(message, handler),
    );
  }
  Future<ByteData> _handleAsMethodCall(ByteData message, Future<dynamic> handler(MethodCall call)) async {
    final MethodCall call = codec.decodeMethodCall(message);
    try {
      return codec.encodeSuccessEnvelope(await handler(call));
    } on PlatformException catch (e) {
      returun ...
    } on MissingPluginException {
      return null;
    } catch (e) {
      return ...
    }
  }
  Future<T> invokeMethod<T>(String method, [dynamic arguments]) async {
    assert(method != null);
    final ByteData result = await BinaryMessages.send(
      name,
      codec.encodeMethodCall(MethodCall(method, arguments)),
    );
    if (result == null) {
      throw MissingPluginException('No implementation found for method $method on channel $name');
    }
    final T typedResult = codec.decodeEnvelope(result);
    return typedResult;
  }
}
複製程式碼
EventChannel
class EventChannel {
  const EventChannel(this.name, [this.codec = const StandardMethodCodec()]);
  final String name;
  final MethodCodec codec;
  Stream<dynamic> receiveBroadcastStream([dynamic arguments]) {
    final MethodChannel methodChannel = MethodChannel(name, codec);
    StreamController<dynamic> controller;
    controller = StreamController<dynamic>.broadcast(onListen: () async {
      BinaryMessages.setMessageHandler(name, (ByteData reply) async {
        ...
      });
      try {
        await methodChannel.invokeMethod<void>('listen', arguments);
      } catch (exception, stack) {
        ...
      }
    }, onCancel: () async {
      BinaryMessages.setMessageHandler(name, null);
      try {
        await methodChannel.invokeMethod<void>('cancel', arguments);
      } catch (exception, stack) {
        ...
      }
    });
    return controller.stream;
  }
}
複製程式碼

這三種Channel都有兩個成員變數:

  • name:表示Channel名字,用於區分不同Platform Channel的唯一標誌,每個Channel使用唯一的name作為其唯一標誌
  • codec: 表示訊息的編解碼器,Flutter採用了二進位制位元組流作為資料傳輸協議:傳送方需要把資料編碼成二進位制資料,接受方再把資料解碼成原始資料.而負責編解碼操作的就是Codec。 每個Channel中都使用到了BinaryMessages,它起到了信使的作用,負責將資訊進行跨平臺的搬運,是訊息傳送和接受的工具。
setMessageHandler

在建立好BasicMessageChannel後,讓其接受來自另一平臺的訊息,BinaryMessenger呼叫它的setMessageHandler方法為其設定一個訊息處理器,配合BinaryMessenger完成訊息的處理以及回覆;

send

在建立好BasicMessageChannel後,可以呼叫它的send方法向另一個平臺傳遞資料。

setMethodCallHandler

設定用於在此MethodChannel上接收方法呼叫的回撥

receiveBroadcastStream

設定廣播流以接收此EventChannel上的事件

Handler

Flutter使用Handler處理Codec解碼後的訊息。三種Platform Channel相對應,Flutter中也定義了三種Handler:

  • MessageHandler: 用於處理字串或者半結構化訊息,定義在BasicMessageChannel中.
  • MethodCallHandler: 用於處理方法呼叫,定義在MethodChannel中.
  • StreamHandler: 用於事件流通訊,定義在EventChannel中

使用Platform Channel時,需要為其註冊一個對應BinaryMessageHandler為其設定對應的Handler。二進位制資料會被BinaryMessageHanler進行處理,首先使用Codec進行解碼操作,然後再分發給具體Handler進行處理。

結語

欲更進一步瞭解Platform Channel設計與實現,可前往深入Flutter技術內幕:Platform Channel設計與實現,關注大神部落格

相關文章