Flutter与原生双向通信BasicMessageChannel(IOS暂未测试)

Flutter与原生双向通信BasicMessageChannel(IOS暂未测试)

Flutter与原生相互通信的3种方式

MethodChannel:实现Flutter与原生(Android,IOS)双向通信
BasicMessageChannel:实现Flutter与原生(Android,IOS) 双向通信
EventChannel:实现原生(Android,iOS)向Flutter发送消息

Demo基础功能实现目标:

实现调用原生方法并进行回调
显示Android手机当前电量

首先在Flutter方面你需要做的是:

创建BasicMessageChannel
创建通信标识 我个人理解为键值 key

//BasicMessageChannel
//'com.basic.message.channel/batteryLevel'为通信标识
static const _batteryLevel= const BasicMessageChannel(
    'com.basic.message.channel/batteryLevel', StandardMessageCodec());

String _batteryLevel1 = '电池电量未知';

//给原生发送消息方法 
Future sendMessage(Map arguments,BasicMessageChannel telOrbattery) async {
  //电量
  Map batteryMap = await_batteryLevel.send(arguments);
  //解析 原生发给 Flutter 的参数
  var code = batteryMap["code"];
  var message = batteryMap["message"];
  setState(() {
    if(batteryMap != null){
      print("code:$code message:$message");
    }
  });
  return batteryMap;
}


build(BuildContext context){
    return new Column(
        children:[
            ElevatedButton(
        onPressed: () {
          sendMessage({"method": "batteryLevel", "ontent": "flutterdata", "code": 100},_platform).then((value){
            setState(() {
              _batteryLevel1 = value.toString();
            });
          });
          print(_batteryLevel1);
        },
        child: new Text('获取电池电量')),
        ]
    );
}

‘com.basic.message.channel/batteryLevel’:需要与Android原生方保持一致
StandardMessageCodec:为参数传递的编码方式

接着我们使用AndroidStudio打开android模块代码:

找到MainActivity,路劲位置:android/app/src/main/java/XXXXXX/MainActivity.java
XXXX为您的包名,有的会以XX/XX/XX/XX层层的形式出现 点下去就好了

MainActivity:

public class MainActivity extends FlutterActivity {
    private BasicMessageChannel mMessageChannel;
    //************************************END********************************************************
    //BasicMessageChannel方式
    //方法封装 key:与flutter交互的key
//                setMessage:返回的数据 Object
    //              methodName:flutter端的方法名
    private void messageChannelFunction(String key, Object setMessage,String methodName) {
        //消息接收监听
        //BasicMessageChannel (主要是传递字符串和一些半结构体的数据)
        //创建通道
        mMessageChannel = new BasicMessageChannel(
                getFlutterEngine().getDartExecutor().getBinaryMessenger(),
                key,
                StandardMessageCodec.INSTANCE);
        // 接收消息监听
        mMessageChannel.setMessageHandler(new BasicMessageChannel.MessageHandler() {
            @Override
            public void onMessage(Object o, BasicMessageChannel.Reply reply) {


                Map arguments = (Map) o;


                //方法名标识
                String lMethod = (String) arguments.get("method");


                //测试 reply.reply()方法 发消息给Flutter
                if (lMethod.equals(methodName)) {
//                    Toast.makeText(Context, "flutter 调用到了 android test", Toast.LENGTH_SHORT).show();
                    //回调Flutter
                    Map resultMap = new HashMap<>();
                    resultMap.put("message", setMessage);
                    resultMap.put("code", 200);
                    //回调 此方法只能使用一次
                    reply.reply(resultMap);
                }
            }
        });
    }


    //重写onCreade方法
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        messageChannelFunction("com.basic.message.channel/batteryLevel",getBatteryLevel(),"batteryLevel");
    }

    //获取手机电量
    private int getBatteryLevel() {
        int batteryLevel = -1;//getSystemService(BATTERY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
            batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
        } else {
            Intent intent = new ContextWrapper(getApplicationContext())
                    .registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            batteryLevel = (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100)
                    / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        }
        return batteryLevel;
    }
}
 
  

需要注意的是:
private void messageChannelFunction(String key, Object setMessage,String methodName) {}
messageChannelFunction(“com.basic.message.channel/batteryLevel”,getBatteryLevel(),“batteryLevel”);

这个地方的“com.basic.message.channel/batteryLevel”需要与Flutter方保持一致

//方法名标识
String lMethod = (String) arguments.get(“method”);中“method”
需要与Flutter中
{“method”: “test2”, “ontent”: “flutter 中的数据”, “code”: 100} method保持一致

接下来就可以运行看看效果了!
Flutter与原生双向通信BasicMessageChannel(IOS暂未测试)_第1张图片
GET√总体思路:

Flutter创建BasicMessageChannel
添加标识(也就是我理解的key),选择编码方式
进行编码发送消息至Android原生
原生按照标识符与相对应Flutter绑定
收到Flutter编码的消息后 带上需要的参数进行回调Flutter

以上只是个人基础理解,如有误导性请联系我删除博客或进行修改
原创不易,希望各位老爷点完赞再走!
转载请注明作者@As.Kai

关注我,一起成长!
@As.Kai

你可能感兴趣的:(Flutter,java,android,flutter,ios)