Flutter 與原生通訊

開發中通常需要 Flutter 端與原生內容進行交互。Flutter 定義了三種不同的Channel

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

BasicMessageChannel

public class FlutterPluginBasicTest implements BasicMessageChannel.MessageHandler{

    private static final String TAG = "FlutterPluginBasicTgp";
    public static String CHANNEL = "com.tgp.flutterapp/plugin";

    static BasicMessageChannel messageChannel;

    public static void registerWith(PluginRegistry.Registrar registrar) {
        messageChannel = new BasicMessageChannel(registrar.messenger(),CHANNEL,StandardMessageCodec.INSTANCE);
        FlutterPluginBasicTest flutterPluginBasicTest = new FlutterPluginBasicTest();
        messageChannel.setMessageHandler(flutterPluginBasicTest);
    }

    /**
     * java 發起通信
     * @param string
     */
    void sendMessage(String string) {
        messageChannel.send(string, new BasicMessageChannel.Reply() {
            @Override
            public void reply(Object o) {
                Log.d(TAG, "reply: "+0);
            }
        });
    }


    /**
     * Flutter 發起的通信
     * @param o
     * @param reply
     */
    @Override
    public void onMessage(Object o, BasicMessageChannel.Reply reply) {
        Log.d(TAG, "onMessage: "+o);
        reply.reply("ok");
    }
}

註冊

 FlutterPluginBasicTest.registerWith(this.registrarFor(FlutterPluginBasicTest.CHANNEL));

Flutter使用

/**
 * 發送
 */
Future<String> sendMessage() async{
  String reply = await messageChannel.send("Flutter send");
  print(reply);
  return reply;
}

/**
 * 接收
 */
void receiveMessage(){
  messageChannel.setMessageHandler((message) async{
    print(message);
    return "is ok";
  });
}

 

MethodChannel

public class FlutterPluginTest implements MethodChannel.MethodCallHandler {

    private static final String TAG = "FlutterPluginTest";

    /**
     * 插件標識
     */
    public static String CHANNEL = "com.tgp.flutterapp/plugin";

    private static String ACTION_LOG = "log";

    private static String LOG_ARGUMENT = "data";

    static MethodChannel channel;

    public static void registerWith(PluginRegistry.Registrar registrar) {
        channel = new MethodChannel(registrar.messenger(), CHANNEL);
        FlutterPluginTest instance = new FlutterPluginTest();
        channel.setMethodCallHandler(instance);
    }

    @Override
    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {

        /**
         * 通過 method 判斷調用方法
         */
        if (methodCall.method.equals(ACTION_LOG)) {
            /**
             * 解析參數
             */
            String text = methodCall.argument(LOG_ARGUMENT);
            if (TextUtils.isEmpty(text)) {
                /**
                 * 錯誤返回
                 */
                result.error("Data is Null",null,null);
            }else {
                Log.d(TAG, "onMethodCall: "+text);
                /**
                 * 成功返回
                 */
                result.success("is ok");
            }
        }else {
            result.notImplemented();
        }
    }
}

註冊

public class MainActivity extends FlutterActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    /**
     * 註冊插件
     */
    FlutterPluginTest.registerWith(this.registrarFor(FlutterPluginTest.CHANNEL));
  }
}

Flutter 調用

import 'package:flutter/services.dart';

/**
 * 名稱要和Java端一致
 */
const channelName = "com.tgp.flutterapp/plugin";

const methodName = "log";

const MethodChannel channel = MethodChannel(channelName);

Future<String> _testLog() async{
  
  Map<String,String> map = {"data":"Flutter Hello !"};
  
  String result = await channel.invokeMethod(methodName,map);
  
  print(result);
}

 

EventChannel 

public class FlutterPluginEventTest implements EventChannel.StreamHandler {

    private static final String TAG = "FlutterPluginEventTest";
    public static String CHANNEL = "com.tgp.flutterapp/plugin";

    static EventChannel channel;

    public static void registerWith(PluginRegistry.Registrar registrar) {
        channel = new EventChannel(registrar.messenger(), CHANNEL);
        FlutterPluginEventTest flutterPluginEventTest = new FlutterPluginEventTest();
        channel.setStreamHandler(flutterPluginEventTest);
    }

    @Override
    public void onListen(Object o, EventChannel.EventSink eventSink) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                        eventSink.success(System.currentTimeMillis());
                    } catch (InterruptedException e) {
                        eventSink.error("error","error",e.getMessage());
                    }
                }
            }
        }).start();

    }

    @Override
    public void onCancel(Object o) {
        Log.i(TAG, "onCancel: "+o);
    }
}

註冊

FlutterPluginEventTest.registerWith(this.registrarFor(FlutterPluginEventTest.CHANNEL));

Flutter

  1.  
import 'dart:async';

import 'package:flutter/services.dart';

/**
 * 名稱要和Java端一致
 */
const channelName = "com.tgp.flutterapp/plugin";

const EventChannel eventChannel = EventChannel(channelName);

StreamSubscription _subcription = null;

void init(void onEvent(String value),Function onError){
  if(_subcription == null) {
    _subcription = eventChannel.receiveBroadcastStream().listen(onEvent,onError: onError);
  }
}

void dispose(){
  if(_subcription !=null){
    _subcription.cancel();
  }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章