Flutter 官方提供 MethodChannel、EventChannel、BasicMessageChannel 三種方式與原生通信
1.MethodChannel
特點:單方請求響應(flutter->原生)
(1) flutter:
static const platform = const MethodChannel('xiaochen.flutter.io/battery');
try {
final int result = await platform.invokeMethod('getBatteryLevel');
} on PlatformException catch (e) {
}
(2)原生:android
private static final String battery= "xiaochen.flutter.io/battery";
new MethodChannel(getFlutterView(), battery).setMethodCallHandler(
new MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, Result result) {
// TODO
if (call.method.equals("getBatteryLevel")) {
//java 核心代碼
int batteryLevel = getBatteryLevel();
if (batteryLevel != -1) {
result.success(batteryLevel);
} else {
result.error("UNAVAILABLE", "Battery level not available.", null);
}
} else {
result.notImplemented();
}
}
}
);
(3)原生: IOS:
FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController;
FlutterMethodChannel* batteryChannel = [FlutterMethodChannel
methodChannelWithName:@"xiaochen.flutter.io/battery"
binaryMessenger:controller];
[batteryChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
// TODO
if ([@"getBatteryLevel" isEqualToString:call.method]) {
//IOS 核心代碼
int batteryLevel = [self getBatteryLevel];
if (batteryLevel == -1) {
result([FlutterError errorWithCode:@"UNAVAILABLE"
message:@"Battery info unavailable"
details:nil]);
} else {
result(@(batteryLevel));
}
} else {
result(FlutterMethodNotImplemented);
}
}];
2.EventChannel
特點:接收數據(原生->flutter)
(1) flutter:
static const EventChannel _eventChannel =
const EventChannel('xiaochen.flutter.io/test');
// 監聽開始
_eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
void _onEvent(Object event) {
print('返回的內容: $event');
}
void _onError(Object error) {
print('返回的錯誤');
}
(2) 原生:android
private static final String test= "xiaochen.flutter.io/test";
private EventChannel.EventSink eventSink;
new EventChannel(getFlutterView(), test).setStreamHandler(
new EventChannel.StreamHandler() {
@Override
public void onListen(Object o, EventChannel.EventSink eventSink) {
this.eventSink = eventSink;
eventSink.success("主動發送消息給flutter");
}
@Override
public void onCancel(Object o) {
}
}
);
(3)原生: IOS:
FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController;
FlutterEventChannel* eventChannel = [FlutterEventChannel eventChannelWithName:@"xiaochen.flutter.io/test" binaryMessenger:controller];
[eventChannel setStreamHandler:self];
//回調函數:
FlutterEventSink eventSink;
- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
eventSink:(FlutterEventSink)events {
eventSink = events;
if (events) {
events(@"主動發送通知到flutter");
}
return nil;
}
/// flutter不再接收
- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments {
[[NSNotificationCenter defaultCenter] removeObserver:self];
eventSink = nil;
return nil;
}
3.BasicMessageChannel
特點:雙通道
(1)flutter:
//發送
static const SendMessage = const BasicMessageChannel('xiaochen.flutter.io/message', StandardMessageCodec());
Future<String> sendMessage() async {
String reply = await SendMessage.send('發送給Native端的數據');
return reply;
}
//接收
static const ReceiveMessage = const BasicMessageChannel('xiaochen.flutter.io/message2', StandardMessageCodec());
void receiveMessage() {
ReceiveMessage.setMessageHandler((message) async {
print('receiveMessage: $message');
return '返回Native端的數據';
});
}
(2)原生 android:
BasicMessageChannel<Object> messageChannel = new BasicMessageChannel<Object>(getFlutterView(), "xiaochen.flutter.io/message", StandardMessageCodec.INSTANCE);
// 接收消息監聽
messageChannel.setMessageHandler(new BasicMessageChannel.MessageHandler<Object>() {
@Override
public void onMessage(Object o, BasicMessageChannel.Reply<Object> reply) {
System.out.println("onMessage: " + o);
reply.reply("返回給flutter的數據");
}
});
BasicMessageChannel<Object> messageChannel2 = new BasicMessageChannel<Object>(getFlutterView(), "samples.flutter.io/message2", StandardMessageCodec.INSTANCE);
// 發送消息
messageChannel2.send("發送給flutter的數據", new BasicMessageChannel.Reply<Object>() {
@Override
public void reply(Object o) {
System.out.println("onReply: " + o);
}
});
(3)原生: IOS:
FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController;
// 初始化定義
FlutterBasicMessageChannel* messageChannel = [FlutterBasicMessageChannel messageChannelWithName:@"xiaochen.flutter.io/message" binaryMessenger:controller];
// 接收消息監聽
[messageChannel setMessageHandler:^(id message, FlutterReply callback) {
NSLog(message);
callback(@"返回flutter端的數據");
}];
FlutterBasicMessageChannel* messageChannel2 = [FlutterBasicMessageChannel messageChannelWithName:@"xiaochen.flutter.io/message2" binaryMessenger:controller];
// 發送消息
[messageChannel2 sendMessage:(@"發送給flutter的數據") reply:^(id reply) {
NSLog(reply);
}];