全面解析Flutter Platform Channel原理

Android社区 收藏文章

前言


我们知道Flutter中通过Platform Channel实现Flutter和原生端的数据传递,那么这些数据是怎么传递的,传递的过程都做了哪些操作,本文将以Android为例带大家一起了解Platform Channel的工作原理。

Flutter定义了三种不同类型的Channel,分别是

  1. BasicMessageChannel:用于传递字符串和半结构化的数据;
  2. MethodChannel:用于传递方法调用;
  3. EventChannel:用于数据流的通信;

本文以MethodChannel为例带大家一起进行源码分析。

MethodChannel源码解析


官方架构图

根据架构图,我们可以看出在Flutter端,MethodChannel允许发送与方法调用相对应的消息。在安卓和iOS原生端,Android上的MethodChannel和iOS上的FlutterMethodChannel启用接收方法调用并发回结果给Flutter端。而这种数据传递方式还可以反向调用。为了保证用户界面保持相应而不卡顿,消息和响应以异步的形式进行传递。

下面根据官方提供的demo一步一步来进行分析其具体实现。官方提供的demo代码地址如下,实现了一个从Flutter端发起的方法调用,从原生端获取电量并返回给Flutter端用于展示。

https://flutter.dev/docs/development/platform-integration/platform-channels

先来看一下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:null Android :null iOS:nil (NSNull when nested)

Dart:bool Android :java.lang.Boolean iOS:NSNumber numberWithBool:

Dart:int Android :java.lang.Integer iOS:NSNumber numberWithInt:

Dart:int, if 32 bits not enough Android :java.lang.Long iOS:NSNumber numberWithLong:

Dart:double Android :java.lang.Double iOS:NSNumber numberWithDouble:

Dart:String Android :java.lang.String
iOS:NSString

Dart:Uint8List Android :byte[] iOS:FlutterStandardTypedData typedDataWithBytes:

Dart:Int32List Android :int[] iOS:FlutterStandardTypedData typedDataWithInt32:

Dart:Int64List Android :long[] iOS:FlutterStandardTypedData typedDataWithInt64:

Dart:Float64List
Android :double[] iOS:FlutterStandardTypedData typedDataWithFloat64:

Dart:List Android :java.util.ArrayList iOS:NSArray

Dart:Map Android :java.util.HashMap iOS: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/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});
      }));
}

这里会将返回的数据处理通过uitaskrunner执行,即会在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对象<span style="font-size: 14px;">flutterJNI的方法调用将消息传递到java层;
  3. java层解码接收到的消息,根据消息内容做指定的逻辑处理,得到结果后进行编码通过jni方法将响应结果返回给c++层;
  4. c++层处理返回的响应结果,并将结果通过发送时保存的dart响应方法对象回调给Dart层;
  5. Dart层通过回调方法对结果数据进行处理,然后通过codec解码数据做后续的操作;
相关标签

扫一扫

在手机上阅读