https://blog.csdn.net/zl18603543572/article/details/96049359
2019-07-16 00:58:13?早起的年輕人?閱讀數 185??收藏?更多
分類專欄:?flutter??flutter 從入門 到精通?
版權聲明:本文為博主原創文章,遵循?CC 4.0 BY-SA?版權協議,轉載請附上原文出處鏈接和本聲明。?
本文鏈接:https://blog.csdn.net/zl18603543572/article/details/96049359
題記:不到最后時刻,千萬別輕言放棄,無論結局成功與否,只要你拼博過,盡力過,一切問心無愧。
Flutter 與 Android iOS 原生的通信有以下三種方式
BasicMessageChannel 實現 Flutter 與 原生(Android 、iOS)雙向通信
MethodChannel 實現 Flutter 與 原生原生(Android 、iOS)雙向通信
EventChannel 實現 原生原生(Android 、iOS)向Flutter 發送消息
本文將實現:(通過 MethodChannel)
實現 Flutter 調用 Android 、iOS 原生的方法并回調Flutter
實現 Flutter 調用 Android 、iOS 原生并打開Android 原生的一個Activity頁面,iOS原生的一個ViewController 頁面
實現 Android 、iOS 原生主動發送消息到 Flutter 中
實現 Android 、iOS 原生中的 TestActivity 頁面主動發送消息到Flutter中
Android 中的效果(本圖還是 BasicMessageChannel 的效果圖,只不過是通過 MethodChannel 方式實現出來了)
ios 中的效果(本圖還是 BasicMessageChannel 的效果圖,只不過是通過 MethodChannel 方式實現出來了)
? ? 例如我們要實現 A 調用 B,B就會觸發,B再調用A,A就會觸發這樣的功能,
? ? 那么我們就需要在 A 中設置 被B調用的監聽方法,在B中設置被A 調用的監聽方法
1 實現Flutter 調用 Andoid iOS原生方法并回調
? ? 在這里約定的數據格式為 {"code":100,"message":"消息","content":內容}
? ? 也就是說雙向發送消息,可能會有多種消息類型來調用不同的功能,
? ? 統一約定數據格式 可以達到編碼的規范性和代碼的可維護性
//創建MethodChannel
? // flutter_and_native_101 為通信標識
? // StandardMessageCodec() 為參數傳遞的 編碼方式
? static const methodChannel = const MethodChannel('flutter_and_native_101');
? //封裝 Flutter 向 原生中 發送消息 的方法
? //method 為方法標識
? //arguments 為參數
? static Future<dynamic> invokNative(String method, {Map arguments}) async {
? ? if (arguments == null) {
? ? ? //無參數發送消息
? ? ? return await methodChannel.invokeMethod(method);
? ? } else {
? ? ? //有參數發送消息
? ? ? return await methodChannel.invokeMethod(method, arguments);
? ? }
? }
觸發調用 ,分別在 三個 Button 的點擊事件中觸發,下面均無向 原生 Android iOS 傳遞參數
? ? ..then((result) {
? ? ? ? //第一種 原生回調 Flutter 的方法
? ? ? ? //此方法只能使用一次
? ? ? ? int code = result["code"];
? ? ? ? String message = result["message"];
? ? ? setState(() {
? ? ? ? ? recive = "invokNative 中的回調 code $code message $message ";
? ? ? ? });
? });
//用來實現 Android iOS 主動觸發 向 Flutter 中發送消息
invokNative("test2");
//用來實現 Flutter 打開 Android iOS 中的一個新的頁面
invokNative("test3");
1.2 實現實現 Android 中監聽方法并回調
Android 的 MainActivity 中注冊消息監聽
private MethodChannel mMethodChannel;
//記著要在 onCreat方法中調用
private void methodChannelFunction() {
????mMethodChannel = new MethodChannel(getFlutterView(), "flutter_and_native_101");
????//設置監聽
????mMethodChannel.setMethodCallHandler(
????????new MethodChannel.MethodCallHandler() {
????????????@Override
????????????public void onMethodCall(MethodCall call, MethodChannel.Result result) {
????????????????String lMethod = call.method;
????????????????// TODO
????????????????if (lMethod.equals("test")) {
????????????????????????Toast.makeText(mContext, "flutter調用到了 android test", Toast.LENGTH_SHORT).show();
????????????????????????Map resultMap = new HashMap<>();
????????????????????????resultMap.put("message", "result.success返回給flutter的數據");
????????????????????????resultMap.put("code", 200);
????????????????????????//發消息至Flutter ? 此方法只能使用一次
???????????????????????result.success(resultMap);
????????????????} else if (lMethod.equals("test2")) {
????????????????????????????Toast.makeText(mContext, "flutter調用到了 android test2", Toast.LENGTH_SHORT).show();
????????????????????????????Map resultMap = new HashMap<>();
????????????????????????????resultMap.put("message", "android主動調用 flutter test 方法");
????????????????????????????resultMap.put("code", 200);
????????????????????????????//主動向Flutter 中發送消息
????????????????????????????mMethodChannel.invokeMethod("test", resultMap);
????????????????????????????//延遲2秒再主動向 Flutter 中發送消息
????????????????????????????mHandler.postDelayed(new Runnable() {
????????????????????????????????????@Override
????????????????????????????????????public void run() {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??????????Map resultMap2 = new HashMap<>();
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??????????resultMap2.put("message", "android主動調用 flutter test 方法");
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??????????resultMap2.put("code", 200);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??????????mMethodChannel.invokeMethod("test2", resultMap2);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ????}
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?}, 2000);
? ? ? ? ? ? ? ? ?} else if (lMethod.equals("test3")) {
????????????????????????????//測試通過Flutter打開Android Activity
????????????????????????????Toast.makeText(mContext, "flutter調用到了 android test3", Toast.LENGTH_SHORT).show();
????????????????????????????Intent lIntent = new Intent(MainActivity.this, TestMethodChannelActivity.class);
????????????????????????????MainActivity.this.startActivity(lIntent);
????????????????????} else {
????????????????????????????result.notImplemented();
????????????????????}
????????????????}
????????????}
????????);
????}
iOS 的 AppDelegate 中
#include "GeneratedPluginRegistrant.h"
#import
//TestViewController 是創建的一個 測試頁面
#import "TestViewController.h"
@implementation AppDelegate{
? ? FlutterMethodChannel* methodChannel;
}
- (BOOL)application:(UIApplication*)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
? ? [GeneratedPluginRegistrant registerWithRegistry:self];
? ? ? ? ... ...
? ? //FlutterMethodChannel 與 Flutter 之間的雙向通信
? ? [self? methodChannelFunction];
? ? ? ? ... ...
? ??return?[super?application:application didFinishLaunchingWithOptions:launchOptions];
}
-(void) methodChannelFunction{
? ? FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController;
? ? //創建 FlutterMethodChannel
? ? // flutter_and_native_101 是通信標識
? ? methodChannel = [FlutterMethodChannel
?? ? ? ? ? ? ? ? ? ? methodChannelWithName:@"flutter_and_native_101"
?? ? ? ? ? ? ? ? ? ? binaryMessenger:controller];
? ? //設置監聽
? ? [methodChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
? ? ? ? // TODO
? ? ? ? NSString *method=call.method;
? ? ? ? if([method isEqualToString:@"test"]) {
? ? ? ? ? ? NSLog(@"flutter 調用到了 ios test");
? ? ? ? ? ? NSMutableDictionary *dic = [NSMutableDictionary dictionary];
? ? ? ? ? ? [dic setObject:@"result.success 返回給flutter的數據" forKey:@"message"];
? ? ? ? ? ? [dic setObject: [NSNumber numberWithInt:200] forKey:@"code"];
? ? ? ? ? ? //FlutterResult回調 發消息至 Flutter 中
? ? ? ? ? ? //此方法只能調用一次
? ? ? ? ? ? result(dic);
? ? ? ? }else? if([method isEqualToString:@"test2"]) {
? ? ? ? ? ? NSLog(@"flutter 調用到了 ios test2");
? ? ? ? ? ? NSMutableDictionary *dic = [NSMutableDictionary dictionary];
? ? ? ? ? ? [dic setObject:@"result.success 返回給flutter的數據" forKey:@"message"];
? ? ? ? ? ? [dic setObject: [NSNumber numberWithInt:200] forKey:@"code"];
? ? ? ? ? ? //通過此方法 可以主動向Flutter中發送消息
? ? ? ? ? ? //可以多次調用
? ? ? ? ? ? [methodChannel invokeMethod:@"test" ?arguments: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 中
在MainActivity中,創建了 MethodChannel 的實例 mMethodChannel,可以在MainActivity 中直接使用 mMethodChannel 實例來向 Flutter 中發送消息。
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("message", "android 主動調用 flutter test 方法");
resultMap.put("code", 200);
//主動向Flutter 中發送消息
mMethodChannel.invokeMethod("test", resultMap);
在其他的 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 resultMap2 = new HashMap<>();
? ? ? ? ? ? ? ? ? ? resultMap2.put("message","android 主動調用 flutter test 方法");
? ? ? ? ? ? ? ? ? ? resultMap2.put("code",200);
? ? ? ? ? ? ? ? ? ? if(mMethodChannel != null) {
? ? ? ? ? ? ? ? ? ? ? ? // 向Flutter 發送消息
? ? ? ? ? ? ? ? ? ? ? ? mMethodChannel.invokeMethod("test2", resultMap2);
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? });
? ? ? ? }
? ? }
}
2.2 實現 Flutter 中監聽調用方法
? //創建MethodChannel
? // flutter_and_native_101 為通信標識
? // StandardMessageCodec() 為參數傳遞的 編碼方式
? static const methodChannel = const MethodChannel('flutter_and_native_101');
? //設置消息監聽
? Future<dynamic> nativeMessageListener() async {
? ? methodChannel.setMethodCallHandler((resultCall) {
? ? ? //處理原生 Android iOS 發送過來的消息
? ? ? MethodCall call = resultCall;
? ? ? String method = call.method;
? ? ? Map arguments = call.arguments;
? ? ? int code = arguments["code"];
? ? ? String message = arguments["message"];
? ? ? setState(() {
? ? ? ? recive += " code $code message $message and method $method ";
? ? ? ? print(recive);
? ? ? });
? ? });
? }
#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"];
? ? ? ? [messageChannel sendMessage:dic];
? ? }
}
- (void)dealloc {
? ? //單條移除觀察者
? ? //[[NSNotificationCenter defaultCenter] removeObserver:self name:@"REFRESH_TABLEVIEW" object:nil];
? ? //移除所有觀察者
? ? [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
文章最后發布于: 2019-07-16