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

前言

在實際的開發中一般須要 Flutter 調用 Native 的功能,或者 Native 調用 Flutter 的功能java

它們之間的通訊主要是經過 Platform Channel 來實現的, 主要有 3channel :api

  • MethodChannel 用於傳遞方法調用
  • EventChannel 用於數據流(event streams)的通訊
  • BasicMessageChannel 用於傳遞字符串和半結構化的信息

下圖以 MethodChannel 爲例, 展現了 FlutterNative 之間的消息傳遞:bash

在這裏插入圖片描述

爲了應用的流暢度, 可以及時響應用戶的操做, FlutterNative 之間消息和響應的傳遞都是異步的, 可是調用 channel api 的時候須要在 主線程 中調用網絡

Platform Channel 支持的數據類型

Platform Channel 經過標準的消息編解碼器來爲咱們在 發送接收 數據時自動 序列化反序列化app

編解碼支持的數據類型有:異步

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 獲取 手機電量 爲例, 在 Flutter 界面中要想獲取 Android/iOS 的電量, 首先要在 Native 編寫獲取電量的功能, 供 Flutter 來調用async

Native 端代碼ide

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) -> {
              // 在主線程中執行
              if (call.method.equals("getBatteryLevel")) {
                // 獲取電量
                int batteryLevel = fetchBatteryLevel();
                if (batteryLevel != -1) {
                  // 將電量返回給 Flutter 調用
                  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 代碼中, 咱們新建了一個 fetchBatteryLevel 函數來獲取電量, 而後 new 一個 MethodChannel 對象函數

這裏須要注意該構造函數的第二個參數 CHANNEL, 這個字符串在稍後的 Flutter 中也要用到post

最後爲 MethodChannel 設置函數調用處理器 MethodCallHandler, 也就是 Flutter 調用 Native 函數的時候會回調這個MethodCallHandler

Flutter 端代碼

class _MyHomePageState extends State<MyHomePage> {
  // 構造函數參數就是上面 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') 會回調 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),
                  )
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
複製代碼

點擊 Flutter 界面上的按鈕就能夠獲取到 Android 手機裏的電量了:

0

MethodChannel 除了使用實現 Flutter 調用 Native 函數, 也能夠 Native 調用 Flutter 函數

首先要在 Native 端調用 invokeMethod 方法, 指定你要調用哪一個 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 調用 Flutter 的 getFlutterContent 函數
    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 中設置 MethodChannelMethodCallHandler, 也就是說 Native 調用了 invokeMethod 方法後, Flutter 怎麼處理:

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

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

上面代碼的主要意思是, 當咱們點擊按鈕調用 Native 裏的函數獲取電量, 而後在 Native 中立馬調用 Flutter 中的 getFlutterContent 函數

而後控制檯就會輸出, 咱們從 Flutter getFlutterContent() 的返回值:

Dart getFlutterContent() result : This is FlutterContent
複製代碼

EventChannel

EventChannel 適用於事件流的通訊, 例如 Native 須要頻繁的發送消息給 Flutter, 好比監聽網絡狀態, 藍牙設備等等而後發送給 Flutter

下面咱們以一個案例來介紹 EventChannel 的使用, 該案例是在 Native 中每秒發送一個事件給 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);
        // 設置流的處理器(StreamHandler)
        channel.setStreamHandler(new EventChannelPlugin());
    }

    @Override
    public void onListen(Object o, EventChannel.EventSink eventSink) {
        // 每隔一秒數字+1
        handler = new Handler(message -> {
            // 而後把數字發送給 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> {
  // 建立 EventChannel
  static const stream = const EventChannel('com.example.flutter_battery/stream');

  int _count = 0;

  StreamSubscription _timerSubscription;

  void _startTimer() {
    if (_timerSubscription == null)
       // 監聽 EventChannel 流, 會觸發 Native onListen回調
      _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 更像是一個消息的通訊, 若是僅僅是簡單的通訊而不是調用某個方法或者是事件流, 可使用 BasicMessageChannel

BasicMessageChannel 也能夠實現 FlutterNative 的雙向通訊, 下面的示例圖就是官方的例子:

點擊 Native FAB 通知 Flutter 更新, 點擊 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();
    // 設置消息處理器
    platform.setMessageHandler(_handlePlatformIncrement);
  }

  // 若是接收到 Native 的消息 則數字+1
  Future<String> _handlePlatformIncrement(String message) async {
    setState(() {
      _counter++;
    });
    // 發送一個空消息
    return _emptyMessage;
  }

  // 點擊 Flutter 中的 FAB 則發消息給 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);
}
複製代碼

關於 FlutterNative 之間的通訊就介紹到這裏了. 總而言之, 若是通訊須要方法調用可使用 MethodChannel, 通訊的時候用到數據流則使用 EventChannel, 若是僅僅是消息通知則可使用 BasicMessageChannel.

Reference

flutter.dev/docs/develo… juejin.im/post/5b84ff… juejin.im/post/5b4c3c… juejin.im/post/5b3ae6…

聯繫我

下面是個人公衆號,乾貨文章不錯過,有須要的能夠關注下,有任何問題能夠聯繫我:

公衆號:  chiclaim
相關文章
相關標籤/搜索