写点什么

Flutter 与 原生交互(Android),含 BATJM 大厂

用户头像
Android架构
关注
发布于: 13 小时前

public void reply(Object o) {


Log.d(TAG, "reply: "+0);


}


});


}


/**


  • Flutter 发起的通信

  • @param o

  • @param reply


*/


@Override


public void onMessage(Object o, BasicMessageChannel.Reply reply) {


Log.d(TAG, "onMessage: "+o);


reply.reply("ok");


}


}


2.注册


3.dart 调用


/**


  • 发送


*/


Future<String> sendMessage() async{


String reply = await messageChannel.send("Flutter send");


print(reply);


return reply;


}


/**


  • 接收


*/


void receiveMessage(){


messageChannel.setMessageHandler((message) async{


print(message);


return "is ok";


});


}


MethodChannel


=============

flutter 调用 原生

1.实现插件


public class FlutterPluginTest implements MethodChannel.MethodCallHandler {


private static final String TAG = "FlutterPluginTest";


/**


  • 插件标识


*/


public static String CHANNEL = "com.mmd.flutterapp/plugin";


private static String ACTION_LOG = "log";


private static String LOG_ARGUMENT = "data";


static MethodChannel channel;


public static void registerWith(PluginRegistry.Registrar registrar) {


channel = new MethodChannel(registrar.messenger(), CHANNEL);


FlutterPluginTest instance = new FlutterPluginTest();


channel.setMethodCallHandler(instance);


}


@Override


public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {


/**


  • 通过 method 判断调用方法


*/


if (methodCall.method.equals(ACTION_LOG)) {


/**


  • 解析参数


*/


String text = methodCall.argument(LOG_ARGUMENT);


if (TextUtils.isEmpty(text)) {


/**


  • 错误返回


*/


result.error("Data is Null",null,null);


}else {


Log.d(TAG, "onMethodCall: "+text);


/**


  • 成功返回


*/


result.success("is ok");


}


}else {


result.notImplemented();


}


}


}


2.注册插件


public class MainActivity extends FlutterActivity {


@Override


protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);


/**


  • 注册插件


*/


FlutterPluginTest.registerWith(this.registrarFor(FlutterPluginTest.CHANNEL));


}


}


3.Flutter 端调用


import 'package:flutter/services.dart';


/**


  • 名称要和 Java 端一致


*/


const channelName = "com.mmd.flutterapp/plugin";


const methodName = "log";


const MethodChannel channel = MethodChannel(channelName);


Future<String> _testLog() async{


Map<String,String> map = {"data":"Flutter Hello !"};


String result = await channel.invokeMethod(methodName,map);


print(result);


}


EventChannel


============

原生发送数据到 Flutter

**1.


《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》
浏览器打开:qq.cn.hn/FTe 免费领取
复制代码


实现插件**


public class FlutterPluginEventTest implements EventChannel.StreamHandler {


private static final String TAG = "FlutterPluginEventTest";


public static String CHANNEL = "com.mmd.flutterapp/plugin";

用户头像

Android架构

关注

还未添加个人签名 2021.10.31 加入

还未添加个人简介

评论

发布
暂无评论
Flutter 与 原生交互(Android),含BATJM大厂