(八)Flutter 和 Native 之間的通信詳解

前言

在實(shí)際的開發(fā)中通常需要 Flutter 調(diào)用 Native 的功能,或者 Native 調(diào)用 Flutter 的功能

它們之間的通信主要是通過 Platform Channel 來實(shí)現(xiàn)的, 主要有 3channel :

  • MethodChannel 用于傳遞方法調(diào)用
  • EventChannel 用于數(shù)據(jù)流(event streams)的通信
  • BasicMessageChannel 用于傳遞字符串和半結(jié)構(gòu)化的信息

下圖以 MethodChannel 為例, 展示了 FlutterNative 之間的消息傳遞:

在這里插入圖片描述

為了應(yīng)用的流暢度, 能夠及時(shí)響應(yīng)用戶的操作, FlutterNative 之間消息和響應(yīng)的傳遞都是異步的, 但是調(diào)用 channel api 的時(shí)候需要在 主線程 中調(diào)用

Platform Channel 支持的數(shù)據(jù)類型

Platform Channel 通過標(biāo)準(zhǔn)的消息編解碼器來為我們?cè)?發(fā)送接收 數(shù)據(jù)時(shí)自動(dòng) 序列化反序列化

編解碼支持的數(shù)據(jù)類型有:

Dart Android iOS
null null nil (NSNull when nested)
bool java.lang.Boolean NSNumber numberWithBool:
int java.lang.Integer NSNumber numberWithInt:
int(if 32 bits not enough) java.lang.Long NSNumber numberWithLong:
double java.lang.Double NSNumber numberWithDouble:
String java.lang.String NSString
Uint8List byte[] FlutterStandardTypedData typedDataWithBytes:
Int32List int[] FlutterStandardTypedData typedDataWithInt32:
Int64List long[] FlutterStandardTypedData typedDataWithInt64:
Float64List double[] FlutterStandardTypedData typedDataWithFloat64:
List java.util.ArrayList NSArray
Map java.util.HashMap NSDictionary

MethodChannel

Flutter 獲取 手機(jī)電量 為例, 在 Flutter 界面中要想獲取 Android/iOS 的電量, 首先要在 Native 編寫獲取電量的功能, 供 Flutter 來調(diào)用

Native 端代碼

public class MainActivity extends FlutterActivity {
  private static final String CHANNEL = "com.example.flutter_battery/battery";
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GeneratedPluginRegistrant.registerWith(this);
    new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
            (call, result) -> {
              // 在主線程中執(zhí)行
              if (call.method.equals("getBatteryLevel")) {
                // 獲取電量
                int batteryLevel = fetchBatteryLevel();
                if (batteryLevel != -1) {
                  // 將電量返回給 Flutter 調(diào)用
                  result.success(batteryLevel);
                } else {
                  result.error("UNAVAILABLE", "Battery level not available.", null);
                }
              } else {
                result.notImplemented();
              }
            });
  }

  // 獲取電量的方法
  private int fetchBatteryLevel() {
    int batteryLevel;
    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;
  }
}

在 Native 代碼中, 我們新建了一個(gè) fetchBatteryLevel 函數(shù)來獲取電量, 然后 new 一個(gè) MethodChannel 對(duì)象

這里需要注意該構(gòu)造函數(shù)的第二個(gè)參數(shù) CHANNEL, 這個(gè)字符串在稍后的 Flutter 中也要用到

最后為 MethodChannel 設(shè)置函數(shù)調(diào)用處理器 MethodCallHandler, 也就是 Flutter 調(diào)用 Native 函數(shù)的時(shí)候會(huì)回調(diào)這個(gè)MethodCallHandler

Flutter 端代碼

class _MyHomePageState extends State<MyHomePage> {
  // 構(gòu)造函數(shù)參數(shù)就是上面 Android 的 CHANNEL 常量
  static const methodChannelBattery = const MethodChannel('com.example.flutter_battery/battery');

  String _batteryLevel = 'Unknown battery level.';

  Future<void> _getBatteryLevel() async {
    String batteryLevel;
    try {
      // invokeMethod('getBatteryLevel') 會(huì)回調(diào) MethodCallHandler
      final int result = await methodChannelBattery.invokeMethod('getBatteryLevel');
      batteryLevel = 'Battery level at $result % .';
    } on PlatformException catch (e) {
      batteryLevel = "Failed to get battery level: '${e.message}'.";
    } on MissingPluginException catch (e) {
      batteryLevel = "plugin undefined";
    }
    setState(() {
      _batteryLevel = batteryLevel;
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        margin: EdgeInsets.only(left: 10, top: 10),
        child: Center(
          child: Column(
            children: [
              Row(
                children: <Widget>[
                  RaisedButton(
                    child: Text(
                      'GetBatteryFromNative',
                      style: TextStyle(fontSize: 12),
                    ),
                    onPressed: _getBatteryLevel,
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 10),
                    child: Text(_batteryLevel),
                  )
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

點(diǎn)擊 Flutter 界面上的按鈕就可以獲取到 Android 手機(jī)里的電量了:

0

MethodChannel 除了使用實(shí)現(xiàn) Flutter 調(diào)用 Native 函數(shù), 也可以 Native 調(diào)用 Flutter 函數(shù)

首先要在 Native 端調(diào)用 invokeMethod 方法, 指定你要調(diào)用哪個(gè) Flutter 方法:

@Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
    if (call.method.equals("getBatteryLevel")) {
        int batteryLevel = fetchBatteryLevel();

        if (batteryLevel != -1) {
            result.success(batteryLevel);
        } else {
            result.error("UNAVAILABLE", "Battery level not available.", null);
        }
    } else {
        result.notImplemented();
    }
    
    // Native 調(diào)用 Flutter 的 getFlutterContent 函數(shù)
    channel.invokeMethod("getFlutterContent", null, new MethodChannel.Result() {
        @Override
        public void success(Object o) {
            Log.e("BatteryPlugin", "Dart getFlutterContent() result : " + o);
        }

        @Override
        public void error(String s, String s1, Object o) {
            Log.e("BatteryPlugin", "Dart getFlutterContent() error : " + s);
        }

        @Override
        public void notImplemented() {
            Log.e("BatteryPlugin", "Dart getFlutterContent() notImplemented");

        }
    });
}

然后在 Flutter 中設(shè)置 MethodChannelMethodCallHandler, 也就是說 Native 調(diào)用了 invokeMethod 方法后, Flutter 怎么處理:

void initState() {
    super.initState();
    methodChannelBattery.setMethodCallHandler(batteryCallHandler);
}

Future<dynamic> batteryCallHandler(MethodCall call) async {
    switch (call.method) {
      case "getFlutterContent":
        return "This is FlutterContent";
    }
}

上面代碼的主要意思是, 當(dāng)我們點(diǎn)擊按鈕調(diào)用 Native 里的函數(shù)獲取電量, 然后在 Native 中立馬調(diào)用 Flutter 中的 getFlutterContent 函數(shù)

然后控制臺(tái)就會(huì)輸出, 我們從 Flutter getFlutterContent() 的返回值:

Dart getFlutterContent() result : This is FlutterContent

EventChannel

EventChannel 適用于事件流的通信, 例如 Native 需要頻繁的發(fā)送消息給 Flutter, 比如監(jiān)聽網(wǎng)絡(luò)狀態(tài), 藍(lán)牙設(shè)備等等然后發(fā)送給 Flutter

下面我們以一個(gè)案例來介紹 EventChannel 的使用, 該案例是在 Native 中每秒發(fā)送一個(gè)事件給 Flutter:

Native 端代碼

public class EventChannelPlugin implements EventChannel.StreamHandler {

    private Handler handler;
    private static final String CHANNEL = "com.example.flutter_battery/stream";
    private int count = 0;

    public static void registerWith(PluginRegistry.Registrar registrar) {
        // 新建 EventChannel, CHANNEL常量的作用和 MethodChannel 一樣的
        final EventChannel channel = new EventChannel(registrar.messenger(), CHANNEL);
        // 設(shè)置流的處理器(StreamHandler)
        channel.setStreamHandler(new EventChannelPlugin());
    }

    @Override
    public void onListen(Object o, EventChannel.EventSink eventSink) {
        // 每隔一秒數(shù)字+1
        handler = new Handler(message -> {
            // 然后把數(shù)字發(fā)送給 Flutter
            eventSink.success(++count);
            handler.sendEmptyMessageDelayed(0, 1000);
            return false;
        });
        handler.sendEmptyMessage(0);

    }

    @Override
    public void onCancel(Object o) {
        handler.removeMessages(0);
        handler = null;
        count = 0;
    }
}

Flutter 端代碼

class _MyHomePageState extends State<MyHomePage> {
  // 創(chuàng)建 EventChannel
  static const stream = const EventChannel('com.example.flutter_battery/stream');

  int _count = 0;

  StreamSubscription _timerSubscription;

  void _startTimer() {
    if (_timerSubscription == null)
       // 監(jiān)聽 EventChannel 流, 會(huì)觸發(fā) Native onListen回調(diào)
      _timerSubscription = stream.receiveBroadcastStream().listen(_updateTimer);
  }

  void _stopTimer() {
    _timerSubscription?.cancel();
    _timerSubscription = null;
    setState(() => _count = 0);
  }

  void _updateTimer(dynamic count) {
    print("--------$count");
    setState(() => _count = count);
  }

  @override
  void dispose() {
    super.dispose();
    _timerSubscription?.cancel();
    _timerSubscription = null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        margin: EdgeInsets.only(left: 10, top: 10),
        child: Center(
          child: Column(
            children: [
              Row(
                children: <Widget>[
                  RaisedButton(
                    child: Text('Start EventChannel',
                        style: TextStyle(fontSize: 12)),
                    onPressed: _startTimer,
                  ),
                  Padding(
                      padding: EdgeInsets.only(left: 10),
                      child: RaisedButton(
                        child: Text('Cancel EventChannel',
                            style: TextStyle(fontSize: 12)),
                        onPressed: _stopTimer,
                      )),
                  Padding(
                    padding: EdgeInsets.only(left: 10),
                    child: Text("$_count"),
                  )
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}

效果如下圖所示:

EventChannel

BasicMessageChannel

BasicMessageChannel 更像是一個(gè)消息的通信, 如果僅僅是簡單的通信而不是調(diào)用某個(gè)方法或者是事件流, 可以使用 BasicMessageChannel

BasicMessageChannel 也可以實(shí)現(xiàn) FlutterNative 的雙向通信, 下面的示例圖就是官方的例子:

image

點(diǎn)擊 Native FAB 通知 Flutter 更新, 點(diǎn)擊 Flutter FAB 通知 Native 更新

Flutter端代碼

class _MyHomePageState extends State<MyHomePage> {
  static const String _channel = 'increment';
  static const String _pong = 'pong';
  static const String _emptyMessage = '';
  static const BasicMessageChannel<String> platform =
      BasicMessageChannel<String>(_channel, StringCodec());

  int _counter = 0;

  @override
  void initState() {
    super.initState();
    // 設(shè)置消息處理器
    platform.setMessageHandler(_handlePlatformIncrement);
  }

  // 如果接收到 Native 的消息 則數(shù)字+1
  Future<String> _handlePlatformIncrement(String message) async {
    setState(() {
      _counter++;
    });
    // 發(fā)送一個(gè)空消息
    return _emptyMessage;
  }

  // 點(diǎn)擊 Flutter 中的 FAB 則發(fā)消息給 Native
  void _sendFlutterIncrement() {
    platform.send(_pong);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('BasicMessageChannel'),
      ),
      body: Container(
          child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Expanded(
            child: Center(
              child: Text(
                  'Platform button tapped $_counter time${_counter == 1 ? '' : 's'}.',
                  style: const TextStyle(fontSize: 17.0)),
            ),
          ),
          Container(
            padding: const EdgeInsets.only(bottom: 15.0, left: 5.0),
            child: Row(
              children: <Widget>[
                Image.asset('assets/flutter-mark-square-64.png', scale: 1.5),
                const Text('Flutter', style: TextStyle(fontSize: 30.0)),
              ],
            ),
          ),
        ],
      )),
      floatingActionButton: FloatingActionButton(
        onPressed: _sendFlutterIncrement,
        child: const Icon(Icons.add),
      ),
    );
  }
}

Native端代碼

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // 省略其他代碼...
    
    messageChannel = new BasicMessageChannel<>(flutterView, CHANNEL, StringCodec.INSTANCE);
    messageChannel.
        setMessageHandler(new MessageHandler<String>() {
            @Override
            public void onMessage(String s, Reply<String> reply) {
                // 接收到Flutter消息, 更新Native
                onFlutterIncrement();
                reply.reply(EMPTY_MESSAGE);
            }
        });

    FloatingActionButton fab = findViewById(R.id.button);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // 通知 Flutter 更新
            sendAndroidIncrement();
        }
    });
}

private void sendAndroidIncrement() {
    messageChannel.send(PING);
}

private void onFlutterIncrement() {
    counter++;
    TextView textView = findViewById(R.id.button_tap);
    String value = "Flutter button tapped " + counter + (counter == 1 ? " time" : " times");
    textView.setText(value);
}

關(guān)于 FlutterNative 之間的通信就介紹到這里了. 總而言之, 如果通信需要方法調(diào)用可以使用 MethodChannel, 通信的時(shí)候用到數(shù)據(jù)流則使用 EventChannel, 如果僅僅是消息通知?jiǎng)t可以使用 BasicMessageChannel.

Reference

https://flutter.dev/docs/development/platform-integration/platform-channels
https://juejin.im/post/5b84ff6a6fb9a019f47d1cc9
https://juejin.im/post/5b4c3c9a5188251ac446d915
https://juejin.im/post/5b3ae6b96fb9a024ba6e0dbb

聯(lián)系我

所有關(guān)于 Retrofit 的使用案例都在我的 AndroidAll GitHub 倉庫中。該倉庫除了 Retrofit,還有其他 Android 其他常用的開源庫源碼分析,如「RxJava」「Glide」「LeakCanary」「Dagger2」「Retrofit」「OkHttp」「ButterKnife」「Router」等。除此之外,還有完整的 Android 程序員所需要的技術(shù)棧思維導(dǎo)圖,歡迎享用。

下面是我的公眾號(hào),干貨文章不錯(cuò)過,有需要的可以關(guān)注下,有任何問題可以聯(lián)系我:

公眾號(hào): chiclaim
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容