題記:不到最後時刻,千萬别輕言放棄,無論結局成功與否,隻要你拼博過,盡力過,一切問心無愧。
通過 Flutter 來進行移動應用開發,打包 Android 、iOS 雙平台應用程式,在調用如相機、藍牙、錄音、鬧鐘、屏保等等系列功能時,需要與原生Android、iOS進行消息通信,或者可描述為把資料由 Flutter 傳向 Android 、iOS,或者由原生的 Android 、iOS傳向 Flutter。
Flutter 與 Android iOS 原生的通信有以下三種方式
- BasicMessageChannel 實作 Flutter 與 原生(Android 、iOS)雙向通信
- MethodChannel 實作 Flutter 與 原生原生(Android 、iOS)雙向通信
- EventChannel 實作 原生原生(Android 、iOS)向Flutter 發送消息
本文将實作:(通過 BasicMessageChannel)
- 實作 Flutter 調用 Android 、iOS 原生的方法并回調Flutter
- 實作 Flutter 調用 Android 、iOS 原生并打開Android 原生的一個Activity頁面,iOS原生的一個ViewController 頁面
- 實作 Android 、iOS 原生主動發送消息到 Flutter 中
- 實作 Android 、iOS 原生中的 TestActivity 頁面主動發送消息到Flutter中
Android 中的效果
ios 中的效果
前言
例如我們要實作 A 調用 B,B就會觸發,B再調用A,A就會觸發這樣的功能,
那麼我們就需要在 A 中設定 被B調用的監聽方法,在B中設定被A 調用的監聽方法
1 實作Flutter 調用 Andoid iOS原生方法并回調
在這裡約定的資料格式為 {"code":100,"message":"消息","content":内容}
也就是說雙向發送消息,可能會有多種消息類型來調用不同的功能,
統一約定資料格式 可以達到編碼的規範性和代碼的可維護性
1.1 實作 Flutter 中調用方法
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});
1.2 實作實作 Android 中監聽方法并回調
Android 的 MainActivity 中注冊消息監聽
flutter 更新之後 FlutterActivity 中沒有 getFlutterView() 方法
使用 getFlutterEngine().getDartExecutor().getBinaryMessenger()代替。
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) {
messageController(o,reply);
}
});
}
///消息的解析處理
privite void messageController(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);
//回調 此方法隻能使用一次 向Flutter中反向回調消息
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);
}
}
1.3 實作實作 iOS 中監聽方法 并回調
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
2 Android 、iOS 原生主動發送消息到 Flutter 中
2.1 實作Android 中主動調動調用方法
在MainActivity中,建立了 BasicMessageChannel
private void channelSendMessage() {
Toast.makeText(mContext, "flutter 調用到了 android test", Toast.LENGTH_SHORT).show();
//建構參數
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("message", "reply.reply 傳回給flutter的資料");
resultMap.put("code", 200);
//向 Flutter 中發送消息
//參數 二可以再次接收到 Flutter 中的回調
//也可以直接使用 mMessageChannel.send(resultMap)
mMessageChannel.send(resultMap, new BasicMessageChannel.Reply<Object>() {
@Override
public void reply(Object o) {
Log.d("mMessageChannel", "mMessageChannel send 回調 " + o);
}
});
}
在其他的 Activity 頁面中,我們就使用不到這個執行個體的,我這裡的一個實作 Android 中建立的Activity 頁面向 Flutter 中發送消息的方法 是廣播機制
在 MainActivity 中注冊廣播,在廣播接收者中通過 BasicMessageChannel
在 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);
}
});
}
}
});
}
}
}
2.2 實作 Flutter 中監聽調用方法
//建立 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 已收到消息';
});
}
2.3 實作 iOS 中主動調動調用方法
#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"
#import <Flutter/Flutter.h>
#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