全面解析Flutter Platform Channel原理

Flutter程式設計指南發表於2019-03-23

前言

我們知道Flutter中通過Platform Channel實現Flutter和原生端的資料傳遞,那麼這些資料是怎麼傳遞的,傳遞的過程都做了哪些操作,本文將以Android為例帶大家一起了解Platform Channel的工作原理。

Flutter定義了三種不同型別的Channel,分別是

  1. BasicMessageChannel:用於傳遞字串和半結構化的資料;
  2. MethodChannel:用於傳遞方法呼叫;
  3. EventChannel:用於資料流的通訊;

本文以MethodChannel為例帶大家一起進行原始碼分析。

MethodChannel原始碼解析

官方架構圖

全面解析Flutter Platform Channel原理

根據架構圖,我們可以看出在Flutter端,MethodChannel允許傳送與方法呼叫相對應的訊息。在安卓和iOS原生端,Android上的MethodChannel和iOS上的FlutterMethodChannel啟用接收方法呼叫併發回結果給Flutter端。而這種資料傳遞方式還可以反向呼叫。為了保證使用者介面保持相應而不卡頓,訊息和響應以非同步的形式進行傳遞。

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

flutter.dev/docs/develo…

先來看一下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物件的編碼過程如下

  • ../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並接收訊息處理的流程就完成了。

總結

先上一張訊息傳遞流程圖

全面解析Flutter Platform Channel原理

通過整個原始碼流程的跟蹤,整個訊息傳送和接收結果的流程分為以下幾步:

  1. Dart層通過以上提到的12種型別包含的型別資料進行編碼,然後通過dart的類似jni的本地介面方法傳遞給c++層;
  2. c++層通過持有java物件flutterJNI的方法呼叫將訊息傳遞到java層;
  3. java層解碼接收到的訊息,根據訊息內容做指定的邏輯處理,得到結果後進行編碼通過jni方法將響應結果返回給c++層;
  4. c++層處理返回的響應結果,並將結果通過傳送時儲存的dart響應方法物件回撥給Dart層;
  5. Dart層通過回撥方法對結果資料進行處理,然後通過codec解碼資料做後續的操作;

說明:

文章轉載自對應的“Flutter程式設計指南”微信公眾號,更多Flutter相關技術文章開啟微信掃描二維碼關注微信公眾號獲取。

全面解析Flutter Platform Channel原理

相關文章