鸿蒙小白,搞这个通信都搞了一天,最后没想到这么简单,记录一下
- 代码位置看图
- 之前一直想着在index.ets文件中实现,代码改来改去,一直都收不到消息,最后发现自己创建 FlutterEngine 实例是不行的,需要通过获取拿到这个实例
- 最后查到需要从FlutterAbility中通过框架来管理 Flutter 引擎的创建和销毁,FlutterEngine 也可以直接获取到
- 修改代码位置后就可以了

import { FlutterAbility, FlutterEngine, MethodCall, MethodChannel, MethodResult } from '@ohos/flutter_ohos';
import { GeneratedPluginRegistrant } from '../plugins/GeneratedPluginRegistrant';
export default class EntryAbility extends FlutterAbility {
private channel: MethodChannel | null = null;
configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
GeneratedPluginRegistrant.registerWith(flutterEngine)
console.info('🐯 调用 FLutter--ohos 通信方法');
this.channel = new MethodChannel(flutterEngine.dartExecutor.getBinaryMessenger(), 'com.ccc.get');
this.channel!.setMethodCallHandler({
onMethodCall: async (call: MethodCall, result: MethodResult) => {
console.info(`🐯 收到消息: ${call.method}`);
switch (call.method) {
case 'init':
result.success('success');
break;
case 'getOnePhone':
let args:Map<string,Any> = call.args;
let data:string = args.get('data');
console.info(`🐯 DB ${data} `);
let msg: Map<string, Any> = JsonStringToMap(data);
if (!msg.has('token')) {
msg.set('token','');
}
if (!msg.has('openid')) {
msg.set('openid','');
}
if (!msg.has('nickName')) {
msg.set('nickName','');
}
if (!msg.has('headImage')) {
msg.set('headImage','');
}
let jsonStr = MapToJsonString(msg);
console.info(`🐯 DB ${jsonStr} `);
this.channel?.invokeMethod('jumpLoginMobile',jsonStr);
result.success('success');
break;
default:
result.notImplemented();
break;
}
}
});
}
}
补充下flutter的代码
IPlatform.get().init();
String xx = await IPlatform.get().getOnePhone();
class IPlatform {
IPlatform();
static IPlatform? instance;
static IPlatform get() {
if (instance == null) {
instance = IPlatform();
}
return instance!;
}
static const platform = MethodChannel('com.ccc.get');
Future init() async {
try {
platform.setMethodCallHandler(flutterMethod);
final value = await platform.invokeMethod('init');
Logs.e('value = ${value}');
} catch (e) {}
}
Future<String> getOnePhone() async {
try {
Map<String, dynamic> map = {};
return await platform.invokeMethod('getOnePhone', map);
} catch (e) {
return '';
}
}
Future<dynamic> flutterMethod(MethodCall call) async {
Logs.e('call.method = ${call.method}');
switch (call.method) {
case 'onEvent':
var data = call.arguments;
break;
case 'jumpLoginMobile':
var data = call.arguments;
break;
}
}
}