更多文章请查看 flutter从入门 到精通
本文章中的完整代码在这里
题记:不到最后时刻,千万别轻言放弃,无论结局成功与否,只要你拼博过,尽力过,一切问心无愧。
Flutter 与 Android iOS 原生的通信有以下三种方式
本文将实现:(通过 BasicMessageChannel)
例如我们要实现 A 调用 B,B就会触发,B再调用A,A就会触发这样的功能,
那么我们就需要在 A 中设置 被B调用的监听方法,在B中设置被A 调用的监听方法
在这里约定的数据格式为 {"code":100,"message":"消息","content":内容}
也就是说双向发送消息,可能会有多种消息类型来调用不同的功能,
统一约定数据格式 可以达到编码的规范性和代码的可维护性
String recive = "";
//创建 BasicMessageChannel
// flutter_and_native_100 为通信标识
// StandardMessageCodec() 为参数传递的 编码方式
static const messageChannel = const BasicMessageChannel(
'flutter_and_native_100', StandardMessageCodec());
//发送消息
Future<Map> sendMessage(Map arguments) async {
Map reply = await messageChannel.send(arguments);
//解析 原生发给 Flutter 的参数
int code = reply["code"];
String message = reply["message"];
//更新 Flutter 中页面显示
setState(() {
recive = "code:$code message:$message";
});
return reply;
}
触发调用 ,分别在 三个 Button 的点击事件中触发
//Flutter 向 Android iOS 中基本的发送消息方式
sendMessage({"method": "test", "ontent": "flutter 中的数据", "code": 100});
//用来实现 Android iOS 主动触发 向 Flutter 中发送消息
sendMessage({"method": "test2", "ontent": "flutter 中的数据", "code": 100});
//用来实现 Flutter 打开 Android iOS 中的一个新的页面
sendMessage({"method": "test3", "ontent": "flutter 中的数据", "code": 100});
Android 的 MainActivity 中注册消息监听
private BasicMessageChannel<Object> mMessageChannel;
private void messageChannelFunction() {
//消息接收监听
//BasicMessageChannel (主要是传递字符串和一些半结构体的数据)
//创建通
mMessageChannel = new BasicMessageChannel<Object>(getFlutterView(), "flutter_and_native_100", StandardMessageCodec.INSTANCE);
// 接收消息监听
mMessageChannel.setMessageHandler(new BasicMessageChannel.MessageHandler<Object>() {
@Override
public void onMessage(Object o, BasicMessageChannel.Reply<Object> reply) {
Map<Object, Object> arguments = (Map<Object, Object>) o;
//方法名标识
String lMethod = (String) arguments.get("method");
//测试 reply.reply()方法 发消息给Flutter
if (lMethod.equals("test")) {
Toast.makeText(mContext, "flutter 调用到了 android test", Toast.LENGTH_SHORT).show();
//回调Flutter
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("message", "reply.reply 返回给flutter的数据");
resultMap.put("code", 200);
//回调 此方法只能使用一次
reply.reply(resultMap);
} else if (lMethod.equals("test2")) {
//测试 mMessageChannel.send 发消息给Flutter
//Android 可通过这个方法来主动向 Flutter中发送消息
//只有Flutter 中注册了消息监听 才能接收到这个方法向 Flutter 中发送的消息
channelSendMessage();
} else if (lMethod.equals("test3")) {
//测试通过Flutter打开Android Activity
Toast.makeText(mContext, "flutter 调用到了 android test3", Toast.LENGTH_SHORT).show();
Intent lIntent = new Intent(MainActivity.this, TestBasicMessageActivity.class);
MainActivity.this.startActivity(lIntent);
}
}
});
}
iOS 的 AppDelegate 中
#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"
#import <Flutter/Flutter.h>
//TestViewController 是创建的一个 测试页面
#import "TestViewController.h"
@implementation AppDelegate{
FlutterBasicMessageChannel* messageChannel;
}
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GeneratedPluginRegistrant registerWithRegistry:self];
... ...
//FlutterBasicMessageChannel 与Flutter 之间的双向通信
[self BasicMessageChannelFunction];
... ...
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
-(void) BasicMessageChannelFunction{
//获取当前的 controller
FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController;
// 初始化定义
// flutter_and_native_100 j
messageChannel = [FlutterBasicMessageChannel messageChannelWithName:@"flutter_and_native_100" binaryMessenger:controller];
// 接收消息监听
[messageChannel setMessageHandler:^(id message, FlutterReply callback) {
NSString *method=message[@"method"];
if ([method isEqualToString:@"test"]) {
NSLog(@"flutter 调用到了 ios test");
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setObject:@"[messageChannel setMessageHandler:^(id message, FlutterReply callback) 返回给flutter的数据" forKey:@"message"];
[dic setObject: [NSNumber numberWithInt:200] forKey:@"code"];
callback(dic);
}else if ([method isEqualToString:@"test2"]) {
NSLog(@"flutter 调用到了 ios test2");
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setObject:@"[messageChannel sendMessage:dic] 返回给flutter的数据" forKey:@"message"];
[dic setObject: [NSNumber numberWithInt:200] forKey:@"code"];
//通过这个方法 iOS可以主动多次 向 Flutter 发送消息
[messageChannel sendMessage:dic];
}else if ([method isEqualToString:@"test3"]) {
NSLog(@"flutter 调用到了 ios test3 打开一个新的页面 ");
TestViewController *testController = [[TestViewController alloc]initWithNibName:@"TestViewController" bundle:nil];
[controller presentViewController:testController animated:YES completion:nil];
}
}];
}
@end
在MainActivity中,创建了 BasicMessageChannel 的实例 mMessageChannel,可以在MainActivity 中直接使用 mMessageChannel 实例来向 Flutter 中发送消息。
private void channelSendMessage() {
Toast.makeText(mContext, "flutter 调用到了 android test", Toast.LENGTH_SHORT).show();
//构建参数
Map resultMap = new HashMap<>();
resultMap.put("message", "reply.reply 返回给flutter的数据");
resultMap.put("code", 200);
//向 Flutter 中发送消息
//参数 二可以再次接收到 Flutter 中的回调
//也可以直接使用 mMessageChannel.send(resultMap)
mMessageChannel.send(resultMap, new BasicMessageChannel.Reply
在其他的 Activity 页面中,我们就使用不到这个实例的,我这里的一个实现 Android 中新建的Activity 页面向 Flutter 中发送消息的方法 是广播机制
在 MainActivity 中注册广播,在广播接收者中通过 BasicMessageChannel 的实例 mMessageChannel 来发送消息。
在 Android 中其他的页面中 发送广播到 MainActivity 中的广播接收者中,这样就实现了Android 中新建的Activity 页面向 Flutter 中发送消息
public class MainActivity extends FlutterActivity {
... ...
Handler mHandler = new Handler(Looper.myLooper());
private MainReceiver mMainReceiver;
@Override
protected void onDestroy() {
super.onDestroy();
//注销广播
unregisterReceiver(mMainReceiver);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
... ...
//注册广播
mMainReceiver = new MainReceiver();
IntentFilter lIntentFilter = new IntentFilter("android.to.flutter");
registerReceiver(mMainReceiver, lIntentFilter);
}
public class MainReceiver extends BroadcastReceiver {
public MainReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "接收到自定义的广播", Toast.LENGTH_SHORT).show();
mHandler.post(new Runnable() {
@Override
public void run() {
Map<String, Object> resultMap2 = new HashMap<>();
resultMap2.put("message", "android 主动调用 flutter test 方法");
resultMap2.put("code", 200);
if (mMessageChannel != null) {
// 向Flutter 发送消息
mMessageChannel.send(resultMap2, new BasicMessageChannel.Reply<Object>() {
@Override
public void reply(Object o) {
System.out.println("android onReply: " + o);
}
});
}
}
});
}
}
}
//创建 BasicMessageChannel
// flutter_and_native_100 为通信标识
// StandardMessageCodec() 为参数传递的 编码方式
static const messageChannel = const BasicMessageChannel(
'flutter_and_native_100', StandardMessageCodec());
//接收消息监听
void receiveMessage() {
messageChannel.setMessageHandler((result) async {
//解析 原生发给 Flutter 的参数
int code = result["code"];
String message = result["message"];
setState(() {
recive = "receiveMessage: code:$code message:$message";
});
return 'Flutter 已收到消息';
});
}
#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"
#import
#import "TestViewController.h"
@implementation AppDelegate{
FlutterBasicMessageChannel* messageChannel;
}
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GeneratedPluginRegistrant registerWithRegistry:self];
//注册通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationFuncion:) name:@"ios.to.flutter" object:nil];
... ...
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
... ...
- (void)notificationFuncion: (NSNotification *) notification {
// iOS 中其他页面向Flutter 中发送消息通过这里
// 本页中 可以直接使用 [messageChannel sendMessage:dic];
//处理消息
NSLog(@"notificationFuncion ");
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
if (messageChannel!=nil) {
[dic setObject:@" [messageChannel sendMessage:dic]; 向Flutter 发送消息 " forKey:@"message"];
[dic setObject: [NSNumber numberWithInt:401] forKey:@"code"];
//主动向Flutter 中发送消息
[messageChannel sendMessage:dic];
}
}
- (void)dealloc {
//单条移除观察者
//[[NSNotificationCenter defaultCenter] removeObserver:self name:@"REFRESH_TABLEVIEW" object:nil];
//移除所有观察者
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end