Flutter与android原生通信

 

Flutter 与 Android/iOS 之间信息交互通过 Platform Channel 进行桥接; Flutter 定义了三种不同的 Channel;但无论是传递方法还是传递事件,其本质上都是数据的传递;

  1. MethodChannel:用于传递方法调用;
  2.  EventChannel:用于数据流信息通信;
  3. BasicMessageChannel:用于传递字符串和半结构化的信息;

每种 Channel 均包含三个成员变量;

  1. name:代表 Channe 唯一标识符,Channel 可以包含多个,但 name 为唯一的;
  2. messager:代表消息发送与接收的工具 BinaryMessenger;
  3. codec:代表消息的编解码器

1、MethodChannel:

flutter代码:

// 调用原生方法
static const methodChannel = const MethodChannel('flutter_and_native_101');

static Future<dynamic> invokNative(String method, {Map arguments}) async {
  if (arguments == null) {
    return await methodChannel.invokeMethod(method);
  } else {
    return await methodChannel.invokeMethod(method, arguments);
  }
}

// 监听原生返回
Future<dynamic> nativeMessageListener() async {
    methodChannel.setMethodCallHandler((resultCall) {
      MethodCall call = resultCall;
      String method = call.method;
      Map arguments = call.arguments;

      int code = arguments["code"];
      String message = arguments["message"];
      setState(() {
        recive += " code $code message $message and method $method \n";
        print(recive);
      });
      return null;
    });
  }

// 调用
onPressed: () {
    invokNative("test")
    ..then((result) {
        int code = result["code"];
        String message = result["message"];
        setState(() {
        	recive = "invokNative 中的回调 code $code message $message ";
        });
    });
}

android代码:

private void methodChannelFunction() {
    mMethodChannel = new MethodChannel(getFlutterView(), "flutter_and_native_101");
    //设置监听
    mMethodChannel.setMethodCallHandler(
            new MethodChannel.MethodCallHandle
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值