Flutter 原生通信 (二) - Android通知Flutter
原生通信系列
1. Flutter 调用 Android
2. Android 通知 Flutter
3. Flutter 调用 iOS
4. iOS 通知 Flutter
第二篇介绍的是原生通知 dart
开篇就是灵魂流程图,自己体会吧 😆
不同于第一篇, 本篇是由 java 端作为发布端, dart 作为订阅端
具体的创建过程请参考第一篇
java
先看看 java 端代码
package com.example.battlepower;
import java.util.Timer;
import java.util.TimerTask;
import io.flutter.plugin.common.BasicMessageChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.Registrar;
import io.flutter.plugin.common.StandardMessageCodec;
/**
* BattlePowerPlugin
*/
public class BattlePowerPlugin implements MethodCallHandler {
private static BasicMessageChannel<Object> runTimeSender;
private static Timer timer;
private static long startTime;
/**
* Plugin registration.
*/
public static void registerWith(Registrar registrar) {
final MethodChannel channel = new MethodChannel(registrar.messenger(), "battle_power");
BattlePowerPlugin handler = new BattlePowerPlugin();
channel.setMethodCallHandler(handler);
runTimeSender = new BasicMessageChannel<>(registrar.messenger(), "run_time", new StandardMessageCodec());
startTime = System.currentTimeMillis();
}
public static void startTimeSender() {
if (timer != null) {
timer.cancel();
} else {
timer = new Timer();
}
timer.schedule(new TimerTask() {
@Override
public void run() {
if (runTimeSender != null) {
runTimeSender.send(System.currentTimeMillis() - startTime);
}
}
}, 5000, 5000);
}
public static void cancelTimer() {
timer.cancel();
}
// ...
}
这里创建BasicMessageChannel
类来负责传递消息
runTimeSender = new BasicMessageChannel<>(registrar.messenger(), "run_time", new StandardMessageCodec());
第一个可以视为固定参数 ,略过不表, 第二个是插件名,需要全应用唯一,第三个是编解码器,如果你看过第一篇,则应该知道了
这个主要功能大概能看懂,就是间隔 5 秒发送一个广播, 广播这个插件的运行时间
dart
static const BasicMessageChannel<dynamic> runTimer = const BasicMessageChannel("run_time", StandardMessageCodec());
static void initMessageHandler() {
runTimer.setMessageHandler((double value) {
// 接收到的时间
int time = value;
print("value = $time");
});
}
这里定义后,就可以从原生端接收到时间了,间隔 5 秒接收一个时间
这里可以看到,dart 端成功的接收到了从原生端发来的消息
通过了两篇 blog 的讲解,flutter <=> android 端的双向通信机制基本都说到了
后面还有 iOS 篇,也是插件开发的必备技能