Flutter 与 Android iOS 原生的通信有以下三种方式
BasicMessageChannel:
用于传递字符串和半结构化的信息,Flutter和平台端进行消息数据交换时候可以使用。
MethodChannel:
用于传递方法调用(method invocation),Flutter和平台端进行直接方法调用时候可以使用。
EventChannel:
用于数据流(event streams)的通信,Flutter和平台端进行事件监听、取消等可以使用。
以下以BasicMessageChannel为例,介绍以下用法:
先创建一个工具类
public class PlatformUtil {
private static String Default_Message_Key = "key_platform_default";
public PlatformUtil(BinaryMessenger binaryMessenger) {
this.binaryMessenger = binaryMessenger;
}
private BasicMessageChannel messageChannel;
private MethodChannel methodChannel;
private EventChannel eventChannel;
private BinaryMessenger binaryMessenger;
public BasicMessageChannel createBasicMessageChannel(String key) {
if (messageChannel == null)
messageChannel = new BasicMessageChannel<>(binaryMessenger, key, StandardMessageCodec.INSTANCE);
return messageChannel;
}
public BasicMessageChannel createBasicMessageChannel() {
return createBasicMessageChannel(Default_Message_Key);
}
public MethodChannel createMethodChannel(String key) {
if (methodChannel == null)
methodChannel = new MethodChannel(binaryMessenger, key, StandardMethodCodec.INSTANCE);
return met