MethodChannel用法
Native端:
构造方法原型
//会构造一个StandardMethodCodec.INSTANCE类型的MethodCodec
MethodChannel(BinaryMessenger messenger, String name)
//或
MethodChannel(BinaryMessenger messenger, String name, MethodCodec codec)
-
BinaryMessenger messenger
- 消息信使,是消息的发送与接收的工具; -
String name
- Channel的名字,也是其唯一标识符; -
MethodCodec codec
- 用作MethodChannel
的编解码器;
setMethodCallHandler方法原型
setMethodCallHandler(@Nullable MethodChannel.MethodCallHandler handler)
-
@Nullable MethodChannel.MethodCallHandler handler
- 消息处理器,配合BinaryMessenger完成消息的处理;
在创建好MethodChannel后,需要调用它的setMessageHandler方法为其设置一个消息处理器,以便能加收来自Dart的消息。
MethodChannel.MethodCallHandler原型
public interface MethodCallHandler {
void onMethodCall(MethodCall var1, MethodChannel.Result var2);
}
-
onMethodCall(MethodCall call, MethodChannel.Result result)
- 用于接受消息,call是消息内容,它有两个成员变量String类型的call.method
表示调用的方法名,Object 类型的call.arguments
表示调用方法所传递的入参;MethodChannel.Result result
是回复此消息的回调函数提供了result.success
,result.error
,result.notImplemented
方法调用;
public class MethodChannelPlugin implements MethodCallHandler {
private final Activity activity;
/**
* Plugin registration.
*/
public static void registerWith(FlutterView flutterView) {
MethodChannel channel = new MethodChannel(flutterView, "MethodChannelPlugin");
MethodChannelPlugin instance = new MethodChannelPlugin((Activity) flutterView.getContext());
channel.setMethodCallHandler(instance);
}
private MethodChannelPlugin(Activity activity) {
this.activity = activity;
}
@Override
public void onMethodCall(MethodCall call, Result result) {
switch (call.method) {//处理来自Dart的方法调用
case "showMessage":
showMessage(call.arguments());
result.success("MethodChannelPlugin收到:" + call.arguments);//返回结果给Dart
break;
default:
result.notImplemented();
}
}
/**
* 展示来自Dart的数据
*
* @param arguments
*/
private void showMessage(String arguments) {
if (activity instanceof IShowMessage) {
((IShowMessage) activity).onShowMessage(arguments);
}
Toast.makeText(activity, arguments, Toast.LENGTH_SHORT).show();
}
}
Dart端:
构造方法原型
const MethodChannel(this.name, [this.codec = const StandardMethodCodec()])
-
String name
- Channel的名字,要和Native端保持一致; -
MethodCodec codec
- 消息的编解码器,默认是StandardMethodCodec,要和Native端保持一致;
invokeMethod方法原型
Future<T> invokeMethod<T>(String method, [ dynamic arguments ])
-
String method
:要调用Native的方法名; -
[ dynamic arguments ]
:调用Native方法传递的参数,可不传;
import 'package:flutter/services.dart';
...
static const MethodChannel _methodChannelPlugin =
const MethodChannel('MethodChannelPlugin');
...
String response;
try {
response = await _methodChannelPlugin.invokeMethod('send', value);
} on PlatformException catch (e) {
print(e);
}
...
EventChannel用法
Native端:
构造方法原型
//会构造一个StandardMethodCodec.INSTANCE类型的MethodCodec
EventChannel(BinaryMessenger messenger, String name)
//或
EventChannel(BinaryMessenger messenger, String name, MethodCodec codec)
-
BinaryMessenger messenger
- 消息信使,是消息的发送与接收的工具; -
String name
- Channel的名字,也是其唯一标识符; -
MethodCodec codec
- 用作EventChannel
的编解码器;
setStreamHandler方法原型
void setStreamHandler(EventChannel.StreamHandler handler)
EventChannel.StreamHandler handler
- 消息处理器,配合BinaryMessenger完成消息的处理;
在创建好EventChannel后,如果要让其接收Dart发来的消息,则需要调用它的setStreamHandler
方法为其设置一个消息处理器。
EventChannel.StreamHandler原型
public interface StreamHandler {
void onListen(Object args, EventChannel.EventSink eventSink);
void onCancel(Object o);
}
-
void onListen(Object args, EventChannel.EventSink eventSink)
- Flutter Native监听事件时调用,Object args
是传递的参数,EventChannel.EventSink eventSink
是Native回调Dart时的会回调函数,eventSink
提供success
、error
与endOfStream
三个回调方法分别对应事件的不同状态; -
void onCancel(Object o)
- Flutter取消监听时调用;
public class EventChannelPlugin implements EventChannel.StreamHandler {
private List<EventChannel.EventSink> eventSinks = new ArrayList<>();
static EventChannelPlugin registerWith(FlutterView flutterView) {
EventChannelPlugin plugin = new EventChannelPlugin();
new EventChannel(flutterView, "EventChannelPlugin").setStreamHandler(plugin);
return plugin;
}
void sendEvent(Object params) {
for (EventChannel.EventSink eventSink : eventSinks) {
eventSink.success(params);
}
}
@Override
public void onListen(Object args, EventChannel.EventSink eventSink) {
eventSinks.add(eventSink);
}
@Override
public void onCancel(Object o) {
}
}
Dart端:
构造方法原型
const EventChannel(this.name, [this.codec = const StandardMethodCodec()]);
-
String name
- Channel的名字,要和Native端保持一致; -
MethodCodec codec
- 消息的编解码器,默认是StandardMethodCodec,要和Native端保持一致;
receiveBroadcastStream
方法原型
Stream<dynamic> receiveBroadcastStream([ dynamic arguments ])
-
dynamic arguments
- 监听事件时向Native传递的数据;
初始化一个广播流用于从channel中接收数据,它返回一个Stream接下来需要调用Stream的listen
方法来完成注册,另外需要在页面销毁时调用Stream的cancel
方法来取消监听;
import 'package:flutter/services.dart';
...
static const EventChannel _eventChannelPlugin =
EventChannel('EventChannelPlugin');
StreamSubscription _streamSubscription;
@override
void initState() {
_streamSubscription=_eventChannelPlugin
.receiveBroadcastStream()
.listen(_onToDart, onError: _onToDartError);
super.initState();
}
@override
void dispose() {
if (_streamSubscription != null) {
_streamSubscription.cancel();
_streamSubscription = null;
}
super.dispose();
}
void _onToDart(message) {
setState(() {
showMessage = message;
});
}
void _onToDartError(error) {
print(error);
}