Flutter 原生通信 (二) - Android通知Flutter

文章目录

原生通信系列





第二篇介绍的是原生通知 dart

开篇就是灵魂流程图,自己体会吧 😆

图片

不同于第一篇, 本篇是由 java 端作为发布端, dart 作为订阅端
具体的创建过程请参考第一篇

java

先看看 java 端代码

 1package com.example.battlepower;
 2
 3import java.util.Timer;
 4import java.util.TimerTask;
 5
 6import io.flutter.plugin.common.BasicMessageChannel;
 7import io.flutter.plugin.common.MethodCall;
 8import io.flutter.plugin.common.MethodChannel;
 9import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
10import io.flutter.plugin.common.MethodChannel.Result;
11import io.flutter.plugin.common.PluginRegistry.Registrar;
12import io.flutter.plugin.common.StandardMessageCodec;
13
14/**
15 * BattlePowerPlugin
16 */
17public class BattlePowerPlugin implements MethodCallHandler {
18
19    private static BasicMessageChannel<Object> runTimeSender;
20
21    private static Timer timer;
22
23    private static long startTime;
24
25    /**
26     * Plugin registration.
27     */
28    public static void registerWith(Registrar registrar) {
29        final MethodChannel channel = new MethodChannel(registrar.messenger(), "battle_power");
30        BattlePowerPlugin handler = new BattlePowerPlugin();
31        channel.setMethodCallHandler(handler);
32
33        runTimeSender = new BasicMessageChannel<>(registrar.messenger(), "run_time", new StandardMessageCodec());
34        startTime = System.currentTimeMillis();
35    }
36
37    public static void startTimeSender() {
38        if (timer != null) {
39            timer.cancel();
40        } else {
41            timer = new Timer();
42        }
43
44        timer.schedule(new TimerTask() {
45            @Override
46            public void run() {
47                if (runTimeSender != null) {
48                    runTimeSender.send(System.currentTimeMillis() - startTime);
49                }
50            }
51        }, 5000, 5000);
52    }
53
54    public static void cancelTimer() {
55        timer.cancel();
56    }
57
58    // ...
59}

这里创建BasicMessageChannel类来负责传递消息

1runTimeSender = new BasicMessageChannel<>(registrar.messenger(), "run_time", new StandardMessageCodec());

第一个可以视为固定参数 ,略过不表, 第二个是插件名,需要全应用唯一,第三个是编解码器,如果你看过第一篇,则应该知道了


这个主要功能大概能看懂,就是间隔 5 秒发送一个广播, 广播这个插件的运行时间

dart

1  static const BasicMessageChannel<dynamic> runTimer = const BasicMessageChannel("run_time", StandardMessageCodec());
2
3  static void initMessageHandler() {
4    runTimer.setMessageHandler((double value) {
5      // 接收到的时间
6      int time = value;
7      print("value = $time");
8    });
9  }

这里定义后,就可以从原生端接收到时间了,间隔 5 秒接收一个时间

图片

这里可以看到,dart 端成功的接收到了从原生端发来的消息


通过了两篇 blog 的讲解,flutter <=> android 端的双向通信机制基本都说到了

后面还有 iOS 篇,也是插件开发的必备技能