全面解析Flutter Platform Channel原理

前言

咱們知道Flutter中經過Platform Channel實現Flutter和原生端的數據傳遞,那麼這些數據是怎麼傳遞的,傳遞的過程都作了哪些操做,本文將以Android爲例帶你們一塊兒瞭解Platform Channel的工做原理。java

Flutter定義了三種不一樣類型的Channel,分別是android

  1. BasicMessageChannel:用於傳遞字符串和半結構化的數據;
  2. MethodChannel:用於傳遞方法調用;
  3. EventChannel:用於數據流的通訊;

本文以MethodChannel爲例帶你們一塊兒進行源碼分析。c++

MethodChannel源碼解析

官方架構圖

根據架構圖,咱們能夠看出在Flutter端,MethodChannel容許發送與方法調用相對應的消息。在安卓和iOS原生端,Android上的MethodChannel和iOS上的FlutterMethodChannel啓用接收方法調用併發回結果給Flutter端。而這種數據傳遞方式還能夠反向調用。爲了保證用戶界面保持相應而不卡頓,消息和響應以異步的形式進行傳遞。shell

下面根據官方提供的demo一步一步來進行分析其具體實現。官方提供的demo代碼地址以下,實現了一個從Flutter端發起的方法調用,從原生端獲取電量並返回給Flutter端用於展現。編程

flutter.dev/docs/develo…api

先來看一下Flutter中dart相關的代碼數組

static const platform = const MethodChannel('samples.flutter.io/battery');

Future<void> _getBatteryLevel() async {
	String batteryLevel;
	try {
	  final int result = await platform.invokeMethod('getBatteryLevel');
	  batteryLevel = 'Battery level at $result % .';
	} on PlatformException catch (e) {
	  batteryLevel = "Failed to get battery level: '${e.message}'.";
	}
	...
}
複製代碼

Dart層方法調用的消息傳遞分析

首先,dart中會先建立一個MethodChannel對象,其名稱爲「samples.flutter.io/battery」,這個名字很關鍵,必須與原生端的名字相對應,具體緣由後邊會有解釋。經過異步方式調用invokeMethod方法傳入方法名來獲取電量信息platform.invokeMethod('getBatteryLevel');,invokeMethod方法具體實現以下緩存

  • ../engine/shell/platform/android/io/flutter/plugin/common/MethodChannel.java
@optionalTypeArgs
  Future<T> invokeMethod<T>(String method, [dynamic arguments]) async {
    assert(method != null);
    final ByteData result = await BinaryMessages.send(
      name,
      codec.encodeMethodCall(MethodCall(method, arguments)),
    );
    if (result == null) {
      throw MissingPluginException('No implementation found for method $method on channel $name');
    }
    final T typedResult = codec.decodeEnvelope(result);
    return typedResult;
  }
複製代碼

經過BinaryMessages.send()方法來發送方法調用消息,咱們能夠看到send方法有兩個參數,第一個是channel的名稱,第二個是ByteData對象(使用codec對根據方法名和參數構建的MethodCall對象進行編碼獲得的對象);codec對象是在MethodChannel對象建立時默認建立的StandardMethodCodec對象,其對MethodCall對象的編碼過程以下bash

  • ../engine/shell/platform/android/io/flutter/plugin/common/StandardMethodCodec.java
@override
ByteData encodeMethodCall(MethodCall call) {
	final WriteBuffer buffer = WriteBuffer();
	messageCodec.writeValue(buffer, call.method);
	messageCodec.writeValue(buffer, call.arguments);
	return buffer.done();
}
複製代碼

經過messageCodec將調用的方法名和傳遞的參數寫入到buffer中,messageCodec是一個StandardMessageCodec對象,在StandardMethodCodec對象建立時默認建立,其writeValue方法的實現以下微信

  • ../engine/shell/platform/android/io/flutter/plugin/common/StandardMessageCodec.java
void writeValue(WriteBuffer buffer, dynamic value) {
    if (value == null) {
      buffer.putUint8(_valueNull);
    } else if (value is bool) {
      buffer.putUint8(value ? _valueTrue : _valueFalse);
    } else if (value is int) {
      if (-0x7fffffff - 1 <= value && value <= 0x7fffffff) {
        buffer.putUint8(_valueInt32);
        buffer.putInt32(value);
      } else {
        buffer.putUint8(_valueInt64);
        buffer.putInt64(value);
      }
    } else if (value is double) {
      buffer.putUint8(_valueFloat64);
      buffer.putFloat64(value);
    } else if (value is String) {
      buffer.putUint8(_valueString);
      final List<int> bytes = utf8.encoder.convert(value);
      writeSize(buffer, bytes.length);
      buffer.putUint8List(bytes);
    } else if (value is Uint8List) {
      buffer.putUint8(_valueUint8List);
      writeSize(buffer, value.length);
      buffer.putUint8List(value);
    } else if (value is Int32List) {
      buffer.putUint8(_valueInt32List);
      writeSize(buffer, value.length);
      buffer.putInt32List(value);
    } else if (value is Int64List) {
      buffer.putUint8(_valueInt64List);
      writeSize(buffer, value.length);
      buffer.putInt64List(value);
    } else if (value is Float64List) {
      buffer.putUint8(_valueFloat64List);
      writeSize(buffer, value.length);
      buffer.putFloat64List(value);
    } else if (value is List) {
      buffer.putUint8(_valueList);
      writeSize(buffer, value.length);
      for (final dynamic item in value) {
        writeValue(buffer, item);
      }
    } else if (value is Map) {
      buffer.putUint8(_valueMap);
      writeSize(buffer, value.length);
      value.forEach((dynamic key, dynamic value) {
        writeValue(buffer, key);
        writeValue(buffer, value);
      });
    } else {
      throw ArgumentError.value(value);
    }
  }
複製代碼

從上述代碼看出,Flutter與平臺端的消息傳遞支持12種類型,這12種類型分別與安卓和iOS中的類型相對應,看下面表格更直觀

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

writeValue方法其實就是將方法名和參數轉化爲對應的二進制數據寫入buffer中,方法名都是String類型,咱們就以String類型方法寫入過程來進行簡單說明,若是判斷一個value爲String後,

  1. 調用buffer.putUint8(_valueString);先寫入對應的類型值,_valueString = 7;,因此將00000111二進制數據寫入buffer;
  2. 緊接着將value經過utf8編碼爲int數組,而後將數組的長度數據經過writeSize(buffer, bytes.length);寫入buffer;
  3. 最後再將數組數據寫入buffer,至此一個方法名編碼完成;

其餘類型的數據依次類推動行編碼,編碼完成後,將StandardMessageCodec對象編碼的ByteData數據經過BinaryMessages.send()方法發送出去,看下send方法的具體實現

  • ../flutter/packages/flutter/lib/src/services/platform_messages.dart
static Future<ByteData> send(String channel, ByteData message) {
	final _MessageHandler handler = _mockHandlers[channel];
	if (handler != null)
	  return handler(message);
	return _sendPlatformMessage(channel, message);
}
複製代碼

會從_mockHandlers中查找是否緩存的有_MessageHandler對象,若是沒有則經過_sendPlatformMessage方法發送消息,

  • ../flutter/packages/flutter/lib/src/services/platform_messages.dart
static Future<ByteData> _sendPlatformMessage(String channel, ByteData message) {
    final Completer<ByteData> completer = Completer<ByteData>();
    ui.window.sendPlatformMessage(channel, message, (ByteData reply) {
      try {
        completer.complete(reply);
      } catch (exception, stack) {
        FlutterError.reportError(FlutterErrorDetails(
          exception: exception,
          stack: stack,
          library: 'services library',
          context: 'during a platform message response callback',
        ));
      }
    });
    return completer.future;
  }
複製代碼

其最終調用的是ui.window.sendPlatformMessage方法,該方法中會傳遞迴調方法對象,在數據返回後會被回調從而獲得結果數據。

  • ../engine/lib/ui/window.dart
void sendPlatformMessage(String name,
                           ByteData data,
                           PlatformMessageResponseCallback callback) {
    final String error =
        _sendPlatformMessage(name, _zonedPlatformMessageResponseCallback(callback), data);
    if (error != null)
      throw new Exception(error);
  }
  String _sendPlatformMessage(String name,
                              PlatformMessageResponseCallback callback,
                              ByteData data) native 'Window_sendPlatformMessage';
複製代碼

在以上代碼中ui.window.sendPlatformMessage()方法最終會調用Dart本地接口方法_sendPlatformMessage,這裏能夠將這個方法簡單理解爲相似於java的JNI的方法,在c++層會調用"Window_sendPlatformMessage"對應的方法。至此,dart中的方法消息傳遞已經結束,咱們下面開始從Flutter engine源碼中分析c++層是如何對方法調用消息進行傳遞的。

c++層消息的傳遞流程分析

咱們在engine源碼文件的./lib/ui/window/window.cc文件中找到了關於dart本地方法的註冊代碼塊

  • ../engine/lib/ui/window/window.cc
void Window::RegisterNatives(tonic::DartLibraryNatives* natives) {
  natives->Register({
      {"Window_defaultRouteName", DefaultRouteName, 1, true},
      {"Window_scheduleFrame", ScheduleFrame, 1, true},
      {"Window_sendPlatformMessage", _SendPlatformMessage, 4, true},
      {"Window_respondToPlatformMessage", _RespondToPlatformMessage, 3, true},
      {"Window_render", Render, 2, true},
      {"Window_updateSemantics", UpdateSemantics, 2, true},
      {"Window_setIsolateDebugName", SetIsolateDebugName, 2, true},
  });
}
複製代碼

經過代碼能夠看到經過tonic::DartLibraryNatives的對象指針調用Register()方法對window對應的多個dart本地方法進行了註冊(說明:該註冊方法的調用是在flutter引擎初始化後Dart虛擬機初始化時調用,這裏再也不對這一塊進行分析,知道便可)。其中就有上面提到的「Window_sendPlatformMessage」,該符號對應到的c++方法爲_SendPlatformMessage,咱們看下該方法中作了些什麼,

  • ../engine/lib/ui/window/window.cc
void _SendPlatformMessage(Dart_NativeArguments args) {
  tonic::DartCallStatic(&SendPlatformMessage, args);
}

Dart_Handle SendPlatformMessage(Dart_Handle window,
                                const std::string& name,
                                Dart_Handle callback,
                                const tonic::DartByteData& data) {
  UIDartState* dart_state = UIDartState::Current();

  ...

  fml::RefPtr<PlatformMessageResponse> response;
  if (!Dart_IsNull(callback)) {
    response = fml::MakeRefCounted<PlatformMessageResponseDart>(
        tonic::DartPersistentValue(dart_state, callback),
        dart_state->GetTaskRunners().GetUITaskRunner());
  }
  if (Dart_IsNull(data.dart_handle())) {
    dart_state->window()->client()->HandlePlatformMessage(
        fml::MakeRefCounted<PlatformMessage>(name, response));
  } else {
    const uint8_t* buffer = static_cast<const uint8_t*>(data.data());

	// data數據部位null,會走下面這塊代碼
    dart_state->window()->client()->HandlePlatformMessage(
        fml::MakeRefCounted<PlatformMessage>(
            name, std::vector<uint8_t>(buffer, buffer + data.length_in_bytes()),
            response));
  }

  return Dart_Null();
}
複製代碼

dart_state是一個UIDartState對象指針,指向當前線程(UI thread)對應的isolate對象Root isolate,回調對象callback不爲null,則會根據dart_statecallback建立一個tonic::DartPersistentValue對象,而後根據當前線程的ui task runner建立一個平臺消息響應對象response(該response會在消息響應結果返回時使用到),接下來走到代碼中註釋下面的代碼塊,其dart_state->window()->client()返回的是Engine對象建立時建立的RuntimeController對象(這個也要回溯到引擎和DartVM初始化的過程,這裏再也不展開,知道便可),下面會調用該對象的HandlePlatformMessage()方法,方法中傳遞的是包含有channel名、方法調用的相關數據和response對象(fml::RefPtr對象,消息響應返回後會使用到)的fml::RefPtr<PlatformMessage>對象。

  • ../engine/runtime/runtime_controller.cc
void RuntimeController::HandlePlatformMessage(
    fml::RefPtr<PlatformMessage> message) {
  client_.HandlePlatformMessage(std::move(message));
}
複製代碼

接着調用client_HandlePlatformMessage()方法,client_是一個繼承了RuntimeDelegate類的Engine對象,

  • ../engine/shell/common/engine.cc
void Engine::HandlePlatformMessage(
    fml::RefPtr<blink::PlatformMessage> message) {
  if (message->channel() == kAssetChannel) {
    HandleAssetPlatformMessage(std::move(message));
  } else {
    delegate_.OnEngineHandlePlatformMessage(std::move(message));
  }
}
複製代碼

由最開始的demo可知channel是咱們自定義的名稱爲「samples.flutter.io/battery」的channel,因此會執行else中的代碼塊,這裏的delegate_是指繼承了Engine::Delegate類的Shell對象,

  • ../engine/shell/common/shell.cc
// |shell::Engine::Delegate|
void Shell::OnEngineHandlePlatformMessage(
    fml::RefPtr<blink::PlatformMessage> message) {
    
  ...
  task_runners_.GetPlatformTaskRunner()->PostTask(
      [view = platform_view_->GetWeakPtr(), message = std::move(message)]() {
        if (view) {
          view->HandlePlatformMessage(std::move(message));
        }
      });
}
複製代碼

因爲Engine的建立是在UI task Runner中即UI thread中建立,因此以上全部消息傳遞都是在UI thread中進行,因爲平臺相關的api都是運行在主線程,立刻要將消息發送給平臺,因此此處會將消息交由platform task Runner執行,即在platform thread中執行方法調用。platform_view_是一個繼承了PlatformView類的PlatformViewAndroid對象,該對象在建立AndroidShellHolder對象時被建立。view->HandlePlatformMessage執行如下方法,

  • ../engine/shell/platform/android/platform_view_android.cc
// |shell::PlatformView|
void PlatformViewAndroid::HandlePlatformMessage(
    fml::RefPtr<blink::PlatformMessage> message) {
  JNIEnv* env = fml::jni::AttachCurrentThread();
  fml::jni::ScopedJavaLocalRef<jobject> view = java_object_.get(env);
  if (view.is_null())
    return;

  int response_id = 0;
  if (auto response = message->response()) {
    response_id = next_response_id_++;
    pending_responses_[response_id] = response;
  }
  auto java_channel = fml::jni::StringToJavaString(env, message->channel());
  if (message->hasData()) {
    fml::jni::ScopedJavaLocalRef<jbyteArray> message_array(
        env, env->NewByteArray(message->data().size()));
    env->SetByteArrayRegion(
        message_array.obj(), 0, message->data().size(),
        reinterpret_cast<const jbyte*>(message->data().data()));
    message = nullptr;

    // This call can re-enter in InvokePlatformMessageXxxResponseCallback.
    FlutterViewHandlePlatformMessage(env, view.obj(), java_channel.obj(),
                                     message_array.obj(), response_id);
  } else {
    ...
  }
}
複製代碼

消息響應對象response不爲空時,建立一個response_id並將其對應response保存到pending_responses_中(消息響應結果返回後會根據response_id取出response對象來處理響應結果),消息數據不爲空時調用if代碼塊中的代碼,而後會調用platform_view_android_jni.cc中的如下方法,view.obj()爲java中的flutterJNI對象,這個對象是在AndroidShellHolder對象建立時從java層傳遞過來的。最後經過env->CallVoidMethod()方法調用java層的flutterJNI對象的handlePlatformMessage方法,將channel名稱、消息內容和響應ID傳給java層。

  • ../engine/shell/platform/android/platform_view_android_jni.cc
static jmethodID g_handle_platform_message_method = nullptr;
void FlutterViewHandlePlatformMessage(JNIEnv* env,
                                      jobject obj,
                                      jstring channel,
                                      jobject message,
                                      jint responseId) {
  env->CallVoidMethod(obj, g_handle_platform_message_method, channel, message,
                      responseId);
  FML_CHECK(CheckException(env));
}
複製代碼

接下來咱們開始分析java層接收到消息後的處理邏輯。

java層接受消息後的處理流程分析

經過以上分析,c++層經過調用flutterJNI的handlePlatformMessage方法將消息傳遞給java層,咱們來看一下FlutterJNI中的方法實現

  • ../engine/shell/platform/android/io/flutter/embedding/engine/FlutterJNI.java
private void handlePlatformMessage(String channel, byte[] message, int replyId) {
    if (this.platformMessageHandler != null) {
        this.platformMessageHandler.handleMessageFromDart(channel, message, replyId);
    }
}
複製代碼

此時會調用platformMessageHandlerhandleMessageFromDart()方法,platformMessageHandler對象是在FlutterNativeView構造方法中建立FlutterJNI對象後設置進來的,是一個實現了PlatformMessageHandler接口的FlutterNativeView.PlatformMessageHandlerImpl對象,咱們看一下它的handleMessageFromDart()方法實現,(最新版本的engine源碼中將處理dart消息的代碼提到了DartMessager類中,請你們注意。)

../engine/shell/platform/android/io/flutter/view/FlutterNativeView.java

public void handleMessageFromDart(final String channel, byte[] message, final int replyId) {
    FlutterNativeView.this.assertAttached();
    BinaryMessageHandler handler = (BinaryMessageHandler)FlutterNativeView.this.mMessageHandlers.get(channel);
    if (handler != null) {
        try {
            ByteBuffer buffer = message == null ? null : ByteBuffer.wrap(message);
            handler.onMessage(buffer, new BinaryReply() {
                private final AtomicBoolean done = new AtomicBoolean(false);

                public void reply(ByteBuffer reply) {
                    if (!FlutterNativeView.this.isAttached()) {
                        Log.d("FlutterNativeView", "handleMessageFromDart replying ot a detached view, channel=" + channel);
                    } else if (this.done.getAndSet(true)) {
                        throw new IllegalStateException("Reply already submitted");
                    } else {
                        if (reply == null) {
                            FlutterNativeView.this.mFlutterJNI.invokePlatformMessageEmptyResponseCallback(replyId);
                        } else {
                            FlutterNativeView.this.mFlutterJNI.invokePlatformMessageResponseCallback(replyId, reply, reply.position());
                        }

                    }
                }
            });
        } catch (Exception var6) {
            Log.e("FlutterNativeView", "Uncaught exception in binary message listener", var6);
            FlutterNativeView.this.mFlutterJNI.invokePlatformMessageEmptyResponseCallback(replyId);
        }

    } else {
        FlutterNativeView.this.mFlutterJNI.invokePlatformMessageEmptyResponseCallback(replyId);
    }
}
複製代碼

首先根據channel名稱從mMessageHandlers中查找對應的BinaryMessageHandler對象,若是找到則執行該對象的onMessage()方法,那麼mMessageHandlers中是怎麼保存咱們的channel名稱爲「samples.flutter.io/battery」的對象的呢,咱們看下開始所說的demo中的java模塊相關代碼,

private static final String CHANNEL = "samples.flutter.io/battery";

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

              if (batteryLevel != -1) {
                result.success(batteryLevel);
              } else {
                result.error("UNAVAILABLE", "Battery level not available.", null);
              }
            } else {
              result.notImplemented();
            }
          }
        });
複製代碼

這塊代碼在MainActivity中的onCreate方法中,建立一個名爲「samples.flutter.io/battery」的MethodChannel對象,而後設置對應的MethodCallHandler對象,setMethodCallHandler的方法實現以下

  • ../engine/shell/platform/android/io/flutter/plugin/common/MethodChannel.java
public void setMethodCallHandler(@Nullable MethodChannel.MethodCallHandler handler) {
    this.messenger.setMessageHandler(this.name, handler == null ? null : new MethodChannel.IncomingMethodCallHandler(handler));
}
複製代碼

其中的messenger就是經過getFlutterView()獲取到的實現了BinaryMessenger接口的FlutterView對象,方法的第二個參數是經過handler對象包裝的MethodChannel.IncomingMethodCallHandler對象,看下FlutterView中對接口方法setMessageHandler()的實現

  • ../engine/shell/platform/android/io/flutter/view/FlutterView.java
public void setMessageHandler(String channel, BinaryMessageHandler handler) {
    this.mNativeView.setMessageHandler(channel, handler);
}
複製代碼

會調用對應的FlutterNativeViewsetMessageHandler()方法,FlutterNativeView一樣實現了BinaryMessenger接口,看下其中的方法實現

  • ../engine/shell/platform/android/io/flutter/view/FlutterNativeView.java
public void setMessageHandler(String channel, BinaryMessageHandler handler) {
    if (handler == null) {
        this.mMessageHandlers.remove(channel);
    } else {
        this.mMessageHandlers.put(channel, handler);
    }
}
複製代碼

到此,咱們發如今MainActivityonCreate方法中實現的MethodCallHandler經過一系列操做被包裝到IncomingMethodCallHandler對象中並設置進了mMessageHandlers中。那麼咱們上面所說的onMessage方法的調用便是IncomingMethodCallHandler對象的方法,

  • ../engine/shell/platform/android/io/flutter/plugin/common/MethodChannel.java
public void onMessage(ByteBuffer message, final BinaryReply reply) {
    MethodCall call = MethodChannel.this.codec.decodeMethodCall(message);

    try {
        this.handler.onMethodCall(call, new MethodChannel.Result() {
            public void success(Object result) {
                reply.reply(MethodChannel.this.codec.encodeSuccessEnvelope(result));
            }

            public void error(String errorCode, String errorMessage, Object errorDetails) {
                reply.reply(MethodChannel.this.codec.encodeErrorEnvelope(errorCode, errorMessage, errorDetails));
            }

            public void notImplemented() {
                reply.reply((ByteBuffer)null);
            }
        });
    } catch (RuntimeException var5) {
        Log.e("MethodChannel#" + MethodChannel.this.name, "Failed to handle method call", var5);
        reply.reply(MethodChannel.this.codec.encodeErrorEnvelope("error", var5.getMessage(), (Object)null));
    }

}
複製代碼

方法中首先將從c++層傳遞過來的消息經過codec解碼爲MethodCall對象,而後調用MainActivity中實現的MethodHandleronMethodCall方法,改方法實現中會獲取當前手機電量信息int batteryLevel = getBatteryLevel();,而後調用result.success()方法,經過reply.reply(MethodChannel.this.codec.encodeSuccessEnvelope(result));將結果數據編碼後進行返回。reply方法中會調用FlutterNativeView.this.mFlutterJNI.invokePlatformMessageResponseCallback(replyId, reply, reply.position());方法將響應結果返回,方法具體實現以下

  • ../engine/shell/platform/android/io/flutter/embedding/engine/FlutterJNI.java
@UiThread
public void invokePlatformMessageResponseCallback(int responseId, ByteBuffer message, int position) {
    this.ensureAttachedToNative();
    this.nativeInvokePlatformMessageResponseCallback(this.nativePlatformViewId, responseId, message, position);
}
    
private native void nativeInvokePlatformMessageResponseCallback(long var1, int var3, ByteBuffer var4, int var5);
複製代碼

最終會調用JNI方法將數據返回給c++層,下面咱們再接着看c++層中接受到響應數據後的處理邏輯。

c++層接收消息響應後的處理流程分析

根據JNI方法動態註冊模塊可知,nativeInvokePlatformMessageResponseCallback方法對應如下c++方法,

  • ../engine/shell/platform/android/platform_view_android_jni.cc
static void InvokePlatformMessageResponseCallback(JNIEnv* env,
                                                  jobject jcaller,
                                                  jlong shell_holder,
                                                  jint responseId,
                                                  jobject message,
                                                  jint position) {
  ANDROID_SHELL_HOLDER->GetPlatformView()
      ->InvokePlatformMessageResponseCallback(env,         //
                                              responseId,  //
                                              message,     //
                                              position     //
      );
}
複製代碼

接着會調用AndroidShellHolder對象持有的PlatformViewAndroid對象的InvokePlatformMessageResponseCallback方法,

  • ../engine/shell/platform/android/platform_view_android.cc
void PlatformViewAndroid::InvokePlatformMessageResponseCallback(
    JNIEnv* env,
    jint response_id,
    jobject java_response_data,
    jint java_response_position) {
  if (!response_id)
    return;
  auto it = pending_responses_.find(response_id);
  if (it == pending_responses_.end())
    return;
  uint8_t* response_data =
      static_cast<uint8_t*>(env->GetDirectBufferAddress(java_response_data));
  std::vector<uint8_t> response = std::vector<uint8_t>(
      response_data, response_data + java_response_position);
  auto message_response = std::move(it->second);
  pending_responses_.erase(it);
  message_response->Complete(
      std::make_unique<fml::DataMapping>(std::move(response)));
}
複製代碼

根據response_idpending_responses_中查找對應的message_response對象,經過對象指針調用其Complete方法處理響應結果,根據以上過程當中代碼的分析可知該方法對應的是繼承了PlatformMessageResponse類的PlatformMessageResponseDart類對象的Complete方法,

  • ../engine/lib/ui/window/platform_message_response_dart.cc
void PlatformMessageResponseDart::Complete(std::unique_ptr<fml::Mapping> data) {
  if (callback_.is_empty())
    return;
  FML_DCHECK(!is_complete_);
  is_complete_ = true;
  ui_task_runner_->PostTask(fml::MakeCopyable(
      [callback = std::move(callback_), data = std::move(data)]() mutable {
        std::shared_ptr<tonic::DartState> dart_state =
            callback.dart_state().lock();
        if (!dart_state)
          return;
        tonic::DartState::Scope scope(dart_state);

        Dart_Handle byte_buffer = WrapByteData(std::move(data));
        tonic::DartInvoke(callback.Release(), {byte_buffer});
      }));
}
複製代碼

這裏會將返回的數據處理經過ui_task_runner執行,即會在UI thread中執行。callback即爲上面分析的dart中對應的回調方法PlatformMessageResponseCallback的對象,經過tonic::DartInvoke()方法將消息返回結果傳遞到dart層進行處理。

Dart層接收消息響應後的處理流程分析

經過以上Dart層傳遞消息分析可知PlatformMessageResponseCallback方法回調後對byte_buffer數據進行處理,經過completer.complete()方法完成返回數據,而後一步步返回到調用方法層,在異步方法中經過await等待數據返回後,再經過setState改變State中的變量值從而刷新頁面數據將電量信息顯示到屏幕上。至此,整個flutter發消息給platform並接收消息處理的流程就完成了。

總結

先上一張消息傳遞流程圖

經過整個源碼流程的跟蹤,整個消息發送和接收結果的流程分爲如下幾步:

  1. Dart層經過以上提到的12種類型包含的類型數據進行編碼,而後經過dart的相似jni的本地接口方法傳遞給c++層;
  2. c++層經過持有java對象flutterJNI的方法調用將消息傳遞到java層;
  3. java層解碼接收到的消息,根據消息內容作指定的邏輯處理,獲得結果後進行編碼經過jni方法將響應結果返回給c++層;
  4. c++層處理返回的響應結果,並將結果經過發送時保存的dart響應方法對象回調給Dart層;
  5. Dart層經過回調方法對結果數據進行處理,而後經過codec解碼數據作後續的操做;

說明:

文章轉載自對應的「Flutter編程指南」微信公衆號,更多Flutter相關技術文章打開微信掃描二維碼關注微信公衆號獲取。

相關文章
相關標籤/搜索