最新的android接受消息改变了
1.flutter发消息到android
flutter 端
//定义通道,作为通信标识符
static const platform = const MethodChannel("add");
//发消息的方法
Future<Null> incrementCount() async {
int result = 0;
try {
//参数为方法名称/消息值
result = await platform.invokeMethod("getNumber","sssss");
} on PlatformException catch (e) {
print(e.message);
}
//获取结果后改变界面状态,更新界面
setState(() {
_counter = result;
});
}
android端
android的mainActivity 内容全替换掉
// 通信标识
private val CHANNEL = "add"
// android发消息到flutter用到
companion object {
var MBinaryMessenger: FlutterEngine? = null
}
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
MBinaryMessenger = flutterEngine// android发消息到flutter用到
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
// Note: this method is invoked on the main thread.
call, result ->
//方法名,通讯标识和方法名来确定执行哪个
if (call.method == "getNumber") {
//call.arguments.toString() 收到的消息值
Log.e("msg",call.arguments.toString() )
// 简介写了 batteryLevel = 一个方法的返回值
// 这里方法返回值为5
val batteryLevel = 5
if (batteryLevel != -1) {
// 返回给flutter接收
result.success(batteryLevel)
} else {
result.error("UNAVAILABLE", "Battery level not available.", null)
}
} else {
result.notImplemented()
}
}
}
2. android发消息给flutter
android端
// 发给flutter的方法 msg为值 access_token为标识符
public void send(String msg) {
BasicMessageChannel basicMessageChannel = new BasicMessageChannel(
MainActivity.Companion.
getMBinaryMessenger().
getDartExecutor().
getBinaryMessenger(), "access_token", StringCodec.INSTANCE);
basicMessageChannel.send(msg);
}
// 我逻辑里面直接调用send不行 就写了个线程
// 不知道是不是必须的,可以自己先测试。
Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch(msg.what){
case 0:
send(msg.obj.toString());
break;
}
}
};
// 发送的消息
Message msg = new Message();
msg.obj = access_token;
msg.what = 0;
mHandler.sendMessage(msg);
flutter端
// 写在initState里面的
@override
void initState() {
super.initState();
//access_token就是标识和android发消息的匹配
const basicMessageChannel = const BasicMessageChannel('access_token', StringCodec());
//接受并回复消息
basicMessageChannel.setMessageHandler(
(String message) => Future<String>(() {
setState(() {
//message 就是接收到的值
_text = message;
});
//可以又给android传回去
return "回复消息";
}),
);
}
开始网上找了好多的都不能用了,去flutter官网上看的(中文官网上好像没有),