flutter 与原生的通信(Android 视角)
Flutter 提供 MethodChannel、EventChannel、BasicMessageChannel 三种方式
flutter 与原生的通信
MethodChannel
由 flutter 发起作为 client 方,native 接收作为 server 方,并能进行消息回传
- flutter:
class FlutterPlugin {
///指定channel名称
static const MethodChannel _channel = const MethodChannel('flutter_plugin');
///发送消息
static Future<String> showToast({String msg}) async {
String result = await _channel.invokeMethod('toast',{"msg":msg});
return result;
}
}
1.渠道名: flutter_plugin
2.方法名: toast
3.参数: {"msg":msg} 参数必须以键值对的方式发送
4.result结果,原生回传消息
发送方参数一定要是键值对
- 原生:
public class FlutterPlugin implements MethodCallHandler {
/**
* Plugin registration.
*/
public static void registerWith(Registrar registrar) {
//1.通道名
MethodChannel channel = new MethodChannel(registrar.messenger(), "flutter_plugin");
channel.setMethodCallHandler(new FlutterPlugin());
}
@Override
public void onMethodCall(MethodCall call, Result result) {
String method = call.method;
//2.对应方法名
switch (method) {
case "getPlatformVersion":
result.success("Android " + android.os.Build.VERSION.RELEASE);
break;
case "toast":
//3.参数名
String msg = call.argument("msg");
Toast.makeText(FlutterAAR.getApp(), msg, Toast.LENGTH_SHORT).show();
//4.返回值
result.success("成功啦");
break;
default:
result.notImplemented();
break;
}
}
}
每回通讯,需协商好这四个位置,需要一一对应
- 注意
本次通讯的方式并没有使用插件,因此GeneratedPluginRegistrant中并不会自动生成对于这个通讯通道的注册,需要自己手动注册,又因为GeneratedPluginRegistrant会每次自动生成,因此,更改GeneratedPluginRegistrant是没有效果的
public class MyGeneratedPluginRegistrant {
public MyGeneratedPluginRegistrant() {
}
public static void registerWith(PluginRegistry registry) {
GeneratedPluginRegistrant.registerWith(registry);
FlutterPlugin.registerWith(registry.registrarFor("io.flutter.plugins.FlutterPlugin"));
}
}
原生与 flutter 的通信
EventChannel
- flutter
///接收消息 1. 渠道: flutter_receive
static const EventChannel _receiver_channel =
const EventChannel('flutter_receive');
///2. 注册接收消息
static void registerReceive(void onData(T),
{bool cancelOnError, void onDone(), Function onError}) {
_receiver_channel.receiveBroadcastStream().listen(
(data) {
if (onData != null) {
onData(data);
}
},
cancelOnError: cancelOnError,
onDone: () {
if (onDone != null) {
onDone();
}
},
onError: (error) {
if (onError != null) {
onError(error);
}
});
}
//使用
@override
void initState() {
super.initState();
FlutterPlugin.registerReceive(
(data) {
final Map<dynamic, dynamic> map = data;
print(map['receive']);
},
cancelOnError: true,
onDone: () {
print('complete');
},
onError: (error) {
if (error is PlatformException) {
print(error.message);
}
});
}
onDone和onError*(error)只会任选其一,走了onError*(error),则不会走onDone了
- 原生
public static void registerWith(Registrar registrar) {
//创建原生接收通道
MethodChannel channel = new MethodChannel(registrar.messenger(), "flutter_send");
//选择通过构造方法的方式,创建原生发送通道
channel.setMethodCallHandler(new FlutterPlugin(registrar));
}
private FlutterPlugin(Registrar registrar){
//1.渠道名
EventChannel eventChannel = new EventChannel(registrar.messenger(),"flutter_receive");
EventChannel.StreamHandler streamHandler = new EventChannel.StreamHandler() {
@Override
public void onListen(Object o, EventChannel.EventSink sink) {
//2.发射器
eventSink = sink;
}
@Override
public void onCancel(Object o) {
eventSink = null;
}
};
eventChannel.setStreamHandler(streamHandler);
}
使用:
HashMap<String, String> hashMap = new HashMap<>(1);
hashMap.put("receive","abc");
eventSink.success(hashMap);
eventSink.error("其实没有错误","其实没有错误2","其实");
eventSink.endOfStream();
发送方参数一定要是键值对