经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » Android » 查看文章
Flutter学习笔记(29)--Flutter如何与native进行通信
来源:cnblogs  作者:CurtisWgh  时间:2019/10/14 9:40:30  对本文有异议

如需转载,请注明出处:Flutter学习笔记(29)--Flutter如何与native进行通信

前言:在我们开发Flutter项目的时候,难免会遇到需要调用native api或者是其他的情况,这时候就需要处理Flutter与native的通信问题,一般常用的Flutter与native的通信方式有3中。

1.MethodChannel:Flutter端向native端发送通知,通常用来调用native的某一个方法。

2.EventChannel:用于数据流的通信,有监听功能,比如电量变化后直接推送给Flutter端。

3.BasicMessageChannel:用于传递字符串或半结构体的数据。

接下来具体看一下每种通信方式的使用方法!

  • MethodChannel

先来整体说一下逻辑思想吧,这样能更容易理解一些,如果想要实现Flutter与native通信,首先要建立一个通信的通道,通过一个通道标识来进行匹配,匹配上了之后Flutter端通过invokeMethod调用方法来发起一个请求,在native端通过onMethodCall进行匹配请求的key,匹配上了就处理对应case内的逻辑!!!整体来看,我感觉有点EventBus的意思呢,就像是一条事件总线。。。

第一步:实现通信插件Plugin-native端

由于一个项目中可能会需要很多Flutter与native的通信,所以我这里是将测试的插件封装到一个类里面了,然后在MainActivity里面的onCreate进行注册

  1. package com.example.flutter_demo;
  2. import android.content.Context;
  3. import io.flutter.plugin.common.MethodCall;
  4. import io.flutter.plugin.common.MethodChannel;
  5. import io.flutter.plugin.common.PluginRegistry;
  6. public class TestPlugin implements MethodChannel.MethodCallHandler {
  7. public static String CHANNELNAME = "channel_name";//每一个通信通道的唯一标识,在整个项目内唯一!!!
  8. private static MethodChannel methodChannel;
  9. private Context context;
  10. public TestPlugin(Context context) {
  11. this.context = context;
  12. }
  13. public static void registerWith(PluginRegistry.Registrar registrar){
  14. methodChannel = new MethodChannel(registrar.messenger(),CHANNELNAME);
  15. TestPlugin instance = new TestPlugin(registrar.activity());
  16. methodChannel.setMethodCallHandler(instance);
  17. }
  18. @Override
  19. public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
  20. if (methodCall.method.equals("method_key")){
  21. result.success("what is up man???");
  22. }
  23. }
  24. }

注:CHANNELNAME-->上面说过了,由于项目内会有很多的通信,所以我们定义的Channel必须是唯一的!!!!

TestPlugin实现MethodChannel.MethodCallHandler,定义一个对外暴露的注册方法registerWith,因为我们需要在MainActivity进行注册,在registerWith方法内初始化MethodChannel

接下来我们看一下onMethodCall方法,这个方法在Flutter发起请求时被调用,方法内有两个参数,一个methodCall和一个result,我们分别来说一下这两个参数:

methodCall:其中当前请求的相关信息,比如匹配请求的key

result:用于给Flutter返回数据,有3个方法,result.success(成功调用)、result.erro(失败调用)、result.notImplemented(方法没有实现调用)

第二步:注册通信插件Plugin-native端

  1. package com.example.flutter_demo;
  2. import android.os.Bundle;
  3. import io.flutter.app.FlutterActivity;
  4. import io.flutter.plugins.GeneratedPluginRegistrant;
  5. public class MainActivity extends FlutterActivity {
  6. @Override
  7. protected void onCreate(Bundle savedInstanceState) {
  8. super.onCreate(savedInstanceState);
  9. GeneratedPluginRegistrant.registerWith(this);
  10. TestPlugin.registerWith(this.registrarFor(TestPlugin.CHANNELNAME));
  11. }
  12. }

注册这块我感觉作用是起到了一个桥梁的作用,通过注册将插件和Flutter内定义的CHANNEL关联了起来。

第三步:Flutter内发起通信请求-flutter端

  1. import 'package:flutter/material.dart';
  2. import 'package:flutter/services.dart';
  3. void main() => runApp(MyApp());
  4. class MyApp extends StatefulWidget{
  5. @override
  6. State<StatefulWidget> createState() {
  7. // TODO: implement createState
  8. return new MyAppState();
  9. }
  10. }
  11. class MyAppState extends State<MyApp> {
  12. var _textContent = 'welcome to flutter word';
  13. Future<Null> _changeTextContent() async{
  14. //channel_name每一个通信通道的唯一标识,在整个项目内唯一!!!
  15. const platfom = const MethodChannel('channel_name');
  16. try {
  17. //method_key是插件TestPlugin中onMethodCall回调匹配的key
  18. String resultValue = await platfom.invokeMethod('method_key');
  19. setState(() {
  20. _textContent = resultValue;
  21. });
  22. }on PlatformException catch (e){
  23. print(e.toString());
  24. }
  25. }
  26. @override
  27. Widget build(BuildContext context) {
  28. // TODO: implement build
  29. return new MaterialApp(
  30. theme: new ThemeData(
  31. primaryColor: Colors.white,
  32. ),
  33. debugShowCheckedModeBanner: false,
  34. title: 'demo',
  35. home: new Scaffold(
  36. appBar: new AppBar(
  37. title: new Text('Demo'),
  38. leading: Icon(Icons.menu,size: 30,),
  39. actions: <Widget>[
  40. Icon(Icons.search,size: 30,)
  41. ],
  42. ),
  43. body: new Center(
  44. child: new Text(_textContent),
  45. ),
  46. floatingActionButton: new FloatingActionButton(onPressed: _changeTextContent,child: new Icon(Icons.adjust),),
  47. ),
  48. );
  49. }
  50. }

这里的功能就是页面中央有一个text,通过点击一个按钮,发起通信请求,通信成功在就收到native返回的数据后将text的文案修改。

我们看一下最终的效果:

                

MethodChannel通信是双向的,也就是说,Flutter端可以向native发起通信,native也可以向Flutter端发起通信,本质上就是反过来调用一下,原理上是同一个意思,具体的代码就不在这里写了,需要的话可以自行百度一下!

  • EventChannel

EventChannel的使用我们也以官方获取电池电量的demo为例,手机的电池状态是不停变化的。我们要把这样的电池状态变化由Native及时通过EventChannel来告诉Flutter。这种情况用之前讲的MethodChannel办法是不行的,这意味着Flutter需要用轮询的方式不停调用getBatteryLevel来获取当前电量,显然是不正确的做法。而用EventChannel的方式,则是将当前电池状态"推送"给Flutter。

第一步:MainActivity内注册EventChannel,并提供获取电量的方法-native端

  1. public class EventChannelPlugin implements EventChannel.StreamHandler {
  2. private Handler handler;
  3. private static final String CHANNEL = "com.example.flutter_battery/stream";
  4. private int count = 0;
  5. public static void registerWith(PluginRegistry.Registrar registrar) {
  6. // 新建 EventChannel, CHANNEL常量的作用和 MethodChannel 一样的
  7. final EventChannel channel = new EventChannel(registrar.messenger(), CHANNEL);
  8. // 设置流的处理器(StreamHandler)
  9. channel.setStreamHandler(new EventChannelPlugin());
  10. }
  11. @Override
  12. public void onListen(Object o, EventChannel.EventSink eventSink) {
  13. // 每隔一秒数字+1
  14. handler = new Handler(message -> {
  15. // 然后把数字发送给 Flutter
  16. eventSink.success(++count);
  17. handler.sendEmptyMessageDelayed(0, 1000);
  18. return false;
  19. });
  20. handler.sendEmptyMessage(0);
  21. }
  22. @Override
  23. public void onCancel(Object o) {
  24. handler.removeMessages(0);
  25. handler = null;
  26. count = 0;
  27. }
  28. }

其中onCancel代表对面不再接收,这里我们应该做一些clean up的事情。而 onListen则代表通道已经建好,Native可以发送数据了。注意onListen里带的EventSink这个参数,后续Native发送数据都是经过EventSink的。

第二步:同MethodChannel一样,发起通信请求

  1. class _MyHomePageState extends State<MyHomePage> {
  2. // 创建 EventChannel
  3. static const stream = const EventChannel('com.example.flutter_battery/stream');
  4. int _count = 0;
  5. StreamSubscription _timerSubscription;
  6. void _startTimer() {
  7. if (_timerSubscription == null)
  8. // 监听 EventChannel 流, 会触发 Native onListen回调
  9. _timerSubscription = stream.receiveBroadcastStream().listen(_updateTimer);
  10. }
  11. void _stopTimer() {
  12. _timerSubscription?.cancel();
  13. _timerSubscription = null;
  14. setState(() => _count = 0);
  15. }
  16. void _updateTimer(dynamic count) {
  17. print("--------$count");
  18. setState(() => _count = count);
  19. }
  20. @override
  21. void dispose() {
  22. super.dispose();
  23. _timerSubscription?.cancel();
  24. _timerSubscription = null;
  25. }
  26. @override
  27. Widget build(BuildContext context) {
  28. return Scaffold(
  29. appBar: AppBar(
  30. title: Text(widget.title),
  31. ),
  32. body: Container(
  33. margin: EdgeInsets.only(left: 10, top: 10),
  34. child: Center(
  35. child: Column(
  36. children: [
  37. Row(
  38. children: <Widget>[
  39. RaisedButton(
  40. child: Text('Start EventChannel',
  41. style: TextStyle(fontSize: 12)),
  42. onPressed: _startTimer,
  43. ),
  44. Padding(
  45. padding: EdgeInsets.only(left: 10),
  46. child: RaisedButton(
  47. child: Text('Cancel EventChannel',
  48. style: TextStyle(fontSize: 12)),
  49. onPressed: _stopTimer,
  50. )),
  51. Padding(
  52. padding: EdgeInsets.only(left: 10),
  53. child: Text("$_count"),
  54. )
  55. ],
  56. )
  57. ],
  58. ),
  59. ),
  60. ),
  61. );
  62. }
  63. }

整体说明一下:Flutter端通过stream.receiveBroadcastStream().listen监听native发送过来的数据,native端通过eventSink.success(++count)不断的将数据返回给Flutter端,这样就实现了我们想要的实时监听的效果了!

  • BasicMessageChannel

其实他就是一个简版的MethodChannel,也可以说MethodChannel是基于BasicMessageChannel实现的,BasicMessageChannel只是进行通信,更通俗的理解就是两端发通知,但是不需要进行方法匹配。

第一步:初始化及注册-native

  1. @Override
  2. protected void onCreate(Bundle savedInstanceState) {
  3. super.onCreate(savedInstanceState);
  4. // 省略其他代码...
  5. messageChannel = new BasicMessageChannel<>(flutterView, CHANNEL, StringCodec.INSTANCE);
  6. messageChannel.
  7. setMessageHandler(new MessageHandler<String>() {
  8. @Override
  9. public void onMessage(String s, Reply<String> reply) {
  10. // 接收到Flutter消息, 更新Native
  11. onFlutterIncrement();
  12. reply.reply(EMPTY_MESSAGE);
  13. }
  14. });
  15. FloatingActionButton fab = findViewById(R.id.button);
  16. fab.setOnClickListener(new View.OnClickListener() {
  17. @Override
  18. public void onClick(View v) {
  19. // 通知 Flutter 更新
  20. sendAndroidIncrement();
  21. }
  22. });
  23. }
  24. private void sendAndroidIncrement() {
  25. messageChannel.send(PING);
  26. }
  27. private void onFlutterIncrement() {
  28. counter++;
  29. TextView textView = findViewById(R.id.button_tap);
  30. String value = "Flutter button tapped " + counter + (counter == 1 ? " time" : " times");
  31. textView.setText(value);
  32. }

第二步:Flutter端发起通信-flutter

  1. class _MyHomePageState extends State<MyHomePage> {
  2. static const String _channel = 'increment';
  3. static const String _pong = 'pong';
  4. static const String _emptyMessage = '';
  5. static const BasicMessageChannel<String> platform =
  6. BasicMessageChannel<String>(_channel, StringCodec());
  7. int _counter = 0;
  8. @override
  9. void initState() {
  10. super.initState();
  11. // 设置消息处理器
  12. platform.setMessageHandler(_handlePlatformIncrement);
  13. }
  14. // 如果接收到 Native 的消息 则数字+1
  15. Future<String> _handlePlatformIncrement(String message) async {
  16. setState(() {
  17. _counter++;
  18. });
  19. // 发送一个空消息
  20. return _emptyMessage;
  21. }
  22. // 点击 Flutter 中的 FAB 则发消息给 Native
  23. void _sendFlutterIncrement() {
  24. platform.send(_pong);
  25. }
  26. @override
  27. Widget build(BuildContext context) {
  28. return Scaffold(
  29. appBar: AppBar(
  30. title: Text('BasicMessageChannel'),
  31. ),
  32. body: Container(
  33. child: Column(
  34. crossAxisAlignment: CrossAxisAlignment.start,
  35. children: <Widget>[
  36. Expanded(
  37. child: Center(
  38. child: Text(
  39. 'Platform button tapped $_counter time${_counter == 1 ? '' : 's'}.',
  40. style: const TextStyle(fontSize: 17.0)),
  41. ),
  42. ),
  43. Container(
  44. padding: const EdgeInsets.only(bottom: 15.0, left: 5.0),
  45. child: Row(
  46. children: <Widget>[
  47. Image.asset('assets/flutter-mark-square-64.png', scale: 1.5),
  48. const Text('Flutter', style: TextStyle(fontSize: 30.0)),
  49. ],
  50. ),
  51. ),
  52. ],
  53. )),
  54. floatingActionButton: FloatingActionButton(
  55. onPressed: _sendFlutterIncrement,
  56. child: const Icon(Icons.add),
  57. ),
  58. );
  59. }
  60. }

 

总结:以上就是Flutter和native通信的全部内容了,理解了以后其实很简单,上面的内容有一些我个人的理解,更深一层的还需要继续挖掘!

原文链接:http://www.cnblogs.com/upwgh/p/11662640.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号