Flutter框架分析-BasicMessageChannel

zuoluohust發表於2021-08-07

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的示例。

相關文章