• Flutter混合开发-通信


    参考:https://www.jianshu.com/p/1a131deeee75

    参考:https://www.jianshu.com/p/1770ded8f50f

    一.混编

    1.咸鱼模式 

    Flutter打包成aar嵌入到原生工程

    2.Google模式,Flutter页面嵌入原生

    public class MyFlutterActivity extends FragmentActivity {
    
    
        FlutterFragment flutterFragment;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_my_flutter);
            
            initFlutterEngine();
            attachFlutterFragment();
        }
    
    
        String ENGINE_ID = "a";
    
        private FlutterEngine initFlutterEngine() {
            FlutterEngine flutterEngine = FlutterEngineCache.getInstance().get(ENGINE_ID);
    
            if (null == flutterEngine) {
                flutterEngine = new FlutterEngine(this);
                flutterEngine.getNavigationChannel().setInitialRoute("/");
                flutterEngine.getDartExecutor().executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault());
                FlutterEngineCache
                        .getInstance()
                        .put(ENGINE_ID, flutterEngine);
                messageChannelFunction(this,flutterEngine);
            }
            return flutterEngine;
        }
    
        private void attachFlutterFragment() {
            if (null == flutterFragment) {
                flutterFragment =
                        FlutterFragment.withCachedEngine(ENGINE_ID)
                                .shouldAttachEngineToActivity(true)
                                .build();
            }
            getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.container, flutterFragment)
                    .commit();
        }
    }
    

      二.通信

    1.BasicMessageChannel 方式

    跨Native,Flutter发送消息可接收消息

    1.1Flutter端给原生发消息

    //Flutter 端

     //创建 BasicMessageChannel
      // flutter_and_native_100 为通信标识
      // StandardMessageCodec() 为参数传递的 编码方式
      static const messageChannel = const BasicMessageChannel(
          'flutter_and_native_100', StandardMessageCodec());
    
      //发送消息
      Future<Map> sendMessage(Map arguments) async {
        Map reply = await messageChannel.send(arguments);
        //解析 原生发给 Flutter 的参数
        int code = reply["code"];
        String message = reply["message"];
    
        //更新 Flutter 中页面显示
        setState(() {
          _counter = "code:$code message:$message";
        });
        return reply;
      }
    

      //原生端

     private BasicMessageChannel<Object> mMessageChannel;
    
        private void messageChannelFunction(Context mContext, FlutterEngine flutterEngine) {
            //消息接收监听
            //BasicMessageChannel (主要是传递字符串和一些半结构体的数据)
            //创建通
            mMessageChannel = new BasicMessageChannel<Object>(flutterEngine.getDartExecutor(), "flutter_and_native_100", StandardMessageCodec.INSTANCE);
            // 接收消息监听
            mMessageChannel.setMessageHandler(new BasicMessageChannel.MessageHandler<Object>() {
                @Override
                public void onMessage(Object o, BasicMessageChannel.Reply<Object> reply) {
    
                    Map<Object, Object> arguments = (Map<Object, Object>) o;
    
                    //方法名标识
                    String lMethod = (String) arguments.get("method");
    
                    //测试 reply.reply()方法 发消息给Flutter
                    if (lMethod.equals("test")) {
                        Toast.makeText(mContext, "flutter 调用到了 android test", Toast.LENGTH_SHORT).show();
                        //回调Flutter
                        Map<String, Object> resultMap = new HashMap<>();
                        resultMap.put("message", "reply.reply 返回给flutter的数据");
                        resultMap.put("code", 200);
                        //回调 此方法只能使用一次
                        reply.reply(resultMap);
    
                    } else if (lMethod.equals("test2")) {
                        //测试 mMessageChannel.send 发消息给Flutter
                        //Android 可通过这个方法来主动向 Flutter中发送消息
                        //只有Flutter 中注册了消息监听 才能接收到这个方法向 Flutter 中发送的消息
    //                    channelSendMessage();
                    } else if (lMethod.equals("test3")) {
                        //测试通过Flutter打开Android Activity
                        Toast.makeText(mContext, "flutter 调用到了 android test3", Toast.LENGTH_SHORT).show();
                        Intent lIntent = new Intent(MyFlutterActivity.this, TestBasicMessageActivity.class);
                        mContext.startActivity(lIntent);
                    }
                }
            });
    
        }
    

      1.2 原生给Flutter发消息

    //原生端

    private void channelSendMessage() {
            mMessageChannel = new BasicMessageChannel<Object>(initFlutterEngine().getDartExecutor(), "flutter_and_native_100", StandardMessageCodec.INSTANCE);
    
            Toast.makeText(this, "flutter 调用到了 android test", Toast.LENGTH_SHORT).show();
            //构建参数
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("message", "reply.reply 返回给flutter的数据");
            resultMap.put("code", 200);
            //向 Flutter 中发送消息
            //参数 二可以再次接收到 Flutter 中的回调
            //也可以直接使用 mMessageChannel.send(resultMap)
            mMessageChannel.send(resultMap, new BasicMessageChannel.Reply<Object>() {
                @Override
                public void reply(Object o) {
                    Log.d("mMessageChannel", "mMessageChannel send 回调 " + o); //消息没有收到???
                }
            });
        }
    

      //Fluttrer 端

     void messageChannelFunction(){
        messageChannel.setMessageHandler((message) async {
          print('message: $message');
          return '返回Native端的数据001';//这是native端的响应 ,执行了
        });
      }
    

      

    2.MethodChannel 方式  

    直接跨Native,Flutter调用方法

    2.1 Native端 发送 + 监听接收

    /**
         * 设置MethodChannel 监听
         *
         * @param flutterEngine
         */
        private void setMethodChannel(FlutterEngine flutterEngine) {
            MethodChannel channel = new MethodChannel(flutterEngine.getDartExecutor(), "study_3/methodChannel");
            channel.setMethodCallHandler(new MethodChannel.MethodCallHandler() {
                @Override
                public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
                    switch (methodCall.method) {
    //                        case NATIVE_METHOD_LOGIN:
    //                            login(context, (String) methodCall.argument("phone"), (String) methodCall.argument("code"));
    //                            break;
                    }
                }
            });
        }
    
        private void invokeMethodChannel(FlutterEngine flutterEngine) {
            MethodChannel channel = new MethodChannel(flutterEngine.getDartExecutor(), "cn.withflutter.plugins.flutter");
            //在Android端调用Flutter中的getInputParams方法,参数是以Json的格式传递。这里是无参方法使用null
            channel.invokeMethod("getInputParams", "{'arg1':'来自Native'}", new MethodChannel.Result() {
    
                @Override
                public void success(@Nullable Object result) {
    
                }
    
                @Override
                public void error(String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails) {
    
                }
    
                @Override
                public void notImplemented() {
    
                }
            });
        }
    

      2.2 Flutter端 发送+监听接收

    class PluginChannel {
      static const _methodChannelName = "study_3/methodChannel";
      static const _methodChannel = MethodChannel(_methodChannelName);
    
      static void invokeMethod() {
        _methodChannel.invokeMethod("getAge", {"name": "lili"}).then((result) {
          print('flutter receive response:$result');
        });
      }
    
      static void listenMethod() {
        _methodChannel.setMethodCallHandler((methodCall) async {
          print('flutter listen:$methodCall');
          return "男";
        });
      }
    }
    

      3.EventChannel 模式

    EventChannel并没有分别提供发送和收听消息的方法,它只提供了一个receiveBroadcastStream方法,用于发送消息,同时返回一个流(Stream),用于监听平台插件成功返回的所有事件信息,这个流可以被监听不止一次。因此我们可以用于native端需要持续传递数据到flutter的情况,比如监听电量,调用摄像头等等
     
    flutter:
    class PluginChannel {
    
      static const _eventChannelName = "study_3/eventChannel";
      static const _eventChannel = EventChannel(_eventChannelName);
    
      static void event() {
        _eventChannel.receiveBroadcastStream("event arg")
            .listen((result) {
          print('flutter listen:$result');
        });
      }
    }
    

      

    android:

    private void eventChannelDemo(FlutterEngine flutterEngine){
    EventChannel channel = new EventChannel(flutterEngine.getDartExecutor(),"study_3/methodChannel");
    channel.setStreamHandler(new EventChannel.StreamHandler() {
    @Override
    public void onListen(Object arguments, EventChannel.EventSink events) {
    events.success(1);
    events.success(2);
    events.success(3);
    events.success(4);
    events.endOfStream();
    }

    @Override
    public void onCancel(Object arguments) {

    }
    });

    }

      



  • 相关阅读:
    Bootstrap3.0入门学习系列教程
    Python——五分钟理解元类(metaclasses)
    Python内置模块和第三方模块
    vs的任务列表
    web.config or app.config 中configSections配置节点
    将查询到的数据导出到Excel终结版
    MVC的一些常用特性,持续更新中。。。
    前端——扫码枪扫码
    前后台数组互传问题解答
    C# 实体/集合差异比较,比较两个实体或集合值是否一样,将实体2的值动态赋值给实体1(名称一样的属性进行赋值)
  • 原文地址:https://www.cnblogs.com/wjw334/p/12693220.html
Copyright © 2020-2023  润新知