flutter和android原生通信的理解(1)
flutter和android原生通信的理解(2)
Flutter层 的Plugin注册
创建 _channel对象
static const _channel = const MethodChannel('vn.hunghd/downloader');
class MethodChannel {
//...
const MethodChannel(this.name, [this.codec = const StandardMethodCodec(), BinaryMessenger binaryMessenger ])
: assert(name != null),
assert(codec != null),
_binaryMessenger = binaryMessenger;
//..
Future<T> _invokeMethod<T>(String method, { bool missingOk, dynamic arguments }) async {
final ByteData result = await binaryMessenger.send(
name,
codec.encodeMethodCall(MethodCall(method, arguments)),
);
if (result == null) {
if (missingOk) {
return null;
}
throw MissingPluginException('No implementation found for method $method on channel $name');
}
return codec.decodeEnvelope(result) as T;
}
MethodChannel 的构造方法中
- 传入 通道名字
- 获取一个BinaryMessenger binaryMessenger 对象;
binaryMessenger 用来发送消息的接口,只不过是 Flutter层的;
binaryMessenger 对象,由ServicesBinding 在初始化时 创建
mixin ServicesBinding on BindingBase {
@override
void initInstances() {
super.initInstances();
_instance = this;
_defaultBinaryMessenger = createBinaryMessenger();
//...
}
Flutter 中 BinaryMessenger是一个接口,实现类是_DefaultBinaryMessenger,
具体功能 是通过 Flutter中的 单例对象 window实现
网友评论