注册

Flutter框架分析-BasicMessageChannel

1. 前言


在文章Flutter框架分析(八)-Platform Channel中,我们分析了BasicMessageChannel的原理和结构,并详细讲解了与其相关的一些核心类,例如MessageHandlerMessageCodec等,本文主要讲解使用BasicMessageChannel的示例。


2. 使用流程


BasicMessageChannel可用于Flutternative发消息,也可用于nativeFlutter发消息,所以接下来将分别分析这两种使用流程。


2.1  Flutter给native发消息


流程如下:


1)native端创建某channel name的BasicMessageChannel


2)native端使用setMessageHandler函数,设置该BasicMessageChannelMessageHandler


3)Flutter端创建该channel name的BasicMessageChannel


4)Flutter端使用该BasicMessageChannel通过send函数向native端发送消息。


5)native端刚刚注册的MessageHandler收到发送的消息,在onMessage中处理消息,通过reply函数进行回复。


6)Flutter端处理该回复。


Flutter端关键代码如下:


class _MessageChannelState extends State<MessageChannelWidget> {
  static const  _channel = BasicMessageChannel('flutter2/testmessagechannel', JSONMessageCodec());
  int i = 0;

  void _sendMessage() async {
    final String reply = await  _channel.send('Hello World i: $i');
    print('MessageChannelTest in dart $reply');
    setState(() {
      i++;
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("message channel test"),
      ),
      body: Center(
         // Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$i',
              style: Theme.*of*(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed:_sendMessage,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),  // This trailing comma makes auto-formatting nicer for build methods);
  }
}

native端关键代码如下:


class MessageChannelActivity: FlutterActivity() {

    companion object {
        fun startActivity(activity: Activity) {
            val intent = Intent(activity, MessageChannelActivity::class.java)
            activity.startActivity(intent)
        }
    }

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {

        Log.d("MessageChannelTest""MessageChannelActivity configureFlutterEngine")
val channel = BasicMessageChannel(
                flutterEngine.dartExecutor.binaryMessenger,
                "flutter2/testmessagechannel",
            JSONMessageCodec.INSTANCE)

         // Receive messages from Dart
channel.setMessageHandler  {message, reply ->
Log.d("MessageChannelTest""in android Received message = $message")
            reply.reply("Reply from Android")
        }
    }
}

2.2  native给Flutter发消息


流程如下:


1) Flutter端创建该channel name的BasicMessageChannel


2) Flutter端使用setMessageHandler函数,设置该BasicMessageChannelHandler函数。


3) native端创建某channel name的BasicMessageChannel


4) native端使用该BasicMessageChannel通过send函数向Flutter端发送消息。


5) Flutter端刚刚注册的Handler收到发送的消息,并处理消息,然后通过reply函数进行回复。


6) native端处理该回复。


Flutter端关键代码如下:


class _MessageChannelState extends State<MessageChannelWidget> {
  static const  _channel = BasicMessageChannel('flutter2/testmessagechannel', JSONMessageCodec());
  int i = 0;

  void _sendMessage() async {
    final String reply = await  _channel.send('Hello World i: $i');
    print('MessageChannelTest in dart $reply');
    setState(() {
      i++;
    });
  }

  @override
  void initState() {
     // Receive messages from platform
_channel.setMessageHandler((dynamic message) async {
      print('MessageChannelTest in dart Received message = $message');
      return 'Reply from Dart';
    });
    super.initState();
  }
}

native端关键代码如下:


class MessageChannelActivity: FlutterActivity() {

    companion object {
        fun startActivity(activity: Activity) {
            val intent = Intent(activity, MessageChannelActivity::class.java)
            activity.startActivity(intent)
        }
    }

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {

        Log.d("MessageChannelTest""MessageChannelActivity configureFlutterEngine")

val channel = BasicMessageChannel(
                flutterEngine.dartExecutor.binaryMessenger,
                "flutter2/testmessagechannel",
            JSONMessageCodec.INSTANCE)

// Send message to Dart
Handler().postDelayed( {
channel.send("Hello World from Android")  { reply ->
Log.d("MessageChannelTest""in android $reply")
             }
}, 500)
    }
}

3. 小结


本文主要介绍了BasicMessageChannel的使用流程,并列举了一个使用BasicMessageChannel的示例。


0 个评论

要回复文章请先登录注册