| 首先来看Android端的代码实现。 public class MethodChannelPlugin implements MethodChannel.MethodCallHandler {  private Activity activity;  private MethodChannel channel;  public static MethodChannelPlugin registerWith(FlutterView flutterView) {  MethodChannel channel = new MethodChannel(flutterView, "MethodChannelPlugin");  MethodChannelPlugin methodChannelPlugin = new MethodChannelPlugin((Activity) flutterView.getContext(), channel);  channel.setMethodCallHandler(methodChannelPlugin);  return methodChannelPlugin;  }  private MethodChannelPlugin(Activity activity, MethodChannel channel) {  this.activity = activity;  this.channel = channel;  }  //调用flutter端方法,无返回值  public void invokeMethod(String method, Object o) {  channel.invokeMethod(method, o);  }  //调用flutter端方法,有返回值  public void invokeMethod(String method, Object o, MethodChannel.Result result) {  channel.invokeMethod(method, o, result);  }  @Override  public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {  switch (methodCall.method) {  case "send"://返回的方法名  //给flutter端的返回值  result.success("MethodChannelPlugin收到:" + methodCall.arguments);  Toast.makeText(activity, methodCall.arguments + "", Toast.LENGTH_SHORT).show();  if (activity instanceof FlutterAppActivity) {  ((FlutterAppActivity) activity).showContent(methodCall.arguments);  }  break;  default:  result.notImplemented();  break;  }  } } 
 笔者对Android端代码做了一个简单的封装,还是很好理解的。下面就来看flutter代码实现。 class _MyHomePageState extends State<MyHomePage> {  MethodChannel _methodChannel = MethodChannel("MethodChannelPlugin");  @override  void initState() {  _methodChannel.setMethodCallHandler((handler) => Future<String>(() {  print("_methodChannel:${handler}");  //监听native发送的方法名及参数  switch (handler.method) {  case "send":  _send(handler.arguments);//handler.arguments表示native传递的方法参数  break;  }  }));  super.initState();  }  //native调用的flutter方法  void _send(arg) {  setState(() {  _content = arg;  });  }  String _resultContent = "";  //flutter调用native的相应方法  void _sendToNative() {  Future<String> future =  _methodChannel.invokeMethod("send", _controller.text);  future.then((message) {  setState(() {  //message是native返回的数据  _resultContent = "返回值:" + message;  });  });  }  @override  Widget build(BuildContext context) {...} } 
 上面就是通过MethodChannel来进行通信的代码实现。还是比较简单的。在Android端使用只需要调用MethodChannelPlugin的invokeMethod方法即可。在flutter端使用只需要参考_sendToNative方法的实现即可。 3.4、BasicMessageChannel (编辑:宣城站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |