目录
1.Flutter的3层架构
2.android开始启动flutter源码分析
3.核心类分析
). FlutterActivityAndFragmentDelegate
). FlutterEngine
).FlutterView
). FlutterEngine
).DartExecutor
4.4个线程比较
5.flutter入库的启动逻辑
1.Flutter架构的核心架构
3层结构.jpgFlutter的架构原理
Flutter架构采用分层设计,从下到上分为三层,依次为:Embedder、Engine、Framework。即嵌入层,引擎层, 框架层
1).Embedder是操作系统适配层,实现了渲染Surface设置,线程设置,以及平台插件等平台相关特性的适配。(操作系统适配层 )
从这里我们可以看到,Flutter平台相关特性并不多,这就使得从框架层面保持跨端一致性的成本相对较低。
2). Engine层主要包含Skia、Dart和Text,实现了Flutter的渲染引擎、文字排版、事件处理和Dart运行时等功能。(渲染,事件)
Skia和Text为上层接口提供了调用底层渲染和排版的能力,Dart则为Flutter提供了运行时调用Dart和渲染引擎的能力。而Engine层的作用,则是将它们组合起来,从它们生成的数据中实现视图渲染。
3). Framework层则是一个用Dart实现的UI SDK,包含了动画、图形绘制和手势识别等功能。(sdk)
为了在绘制控件等固定样式的图形时提供更直观、更方便的接口,Flutter还基于这些基础能力,根据Material和Cupertino两种视觉设计风格封装了一套UI组件库。我们在开发Flutter的时候,可以直接使用这些组件库。
2.启动源码分析
如果我们想要查看 Flutter 引擎底层源码,就需要用到 Ninja 编译, Ninja 的安装步骤可以点击查看
需要从3大结构讲解出源码分析的内容!
- FlutterApplication.java的onCreate过程:初始化配置文件/加载libflutter.so/注册JNI方法;
如果是纯flutter项目, 入口就是这个, 最终调用到main.dart里面的runAPP
架构图如下:
11111.jpg 调用顺序.jpgclass MainActivity: FlutterActivity() {
}
onCreate: 创建FlutterView、Dart虚拟机、Engine、Isolate、taskRunner等对象,最终执行执行到Dart的main()方法,处理整个Dart业务代码。
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
switchLaunchThemeForNormalTheme();
super.onCreate(savedInstanceState);
delegate = new FlutterActivityAndFragmentDelegate(this);
delegate.onAttach(this);
delegate.onRestoreInstanceState(savedInstanceState);
lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
configureWindowForTransparency();
setContentView(createFlutterView());
configureStatusBarForFullscreenFlutterExperience();
}
FlutterActivityAndFragmentDelegate
代理类: 基本上view和引擎都是它创建的!
onAttach: 各种初始化操作
void onAttach(@NonNull Context context) {
ensureAlive();
// When "retain instance" is true, the FlutterEngine will survive configuration
// changes. Therefore, we create a new one only if one does not already exist.
if (flutterEngine == null) {
setupFlutterEngine();
}
if (host.shouldAttachEngineToActivity()) {
// Notify any plugins that are currently attached to our FlutterEngine that they
// are now attached to an Activity.
//
// Passing this Fragment's Lifecycle should be sufficient because as long as this Fragment
// is attached to its Activity, the lifecycles should be in sync. Once this Fragment is
// detached from its Activity, that Activity will be detached from the FlutterEngine, too,
// which means there shouldn't be any possibility for the Fragment Lifecycle to get out of
// sync with the Activity. We use the Fragment's Lifecycle because it is possible that the
// attached Activity is not a LifecycleOwner.
Log.v(TAG, "Attaching FlutterEngine to the Activity that owns this delegate.");
flutterEngine.getActivityControlSurface().attachToActivity(this, host.getLifecycle());
}
// Regardless of whether or not a FlutterEngine already existed, the PlatformPlugin
// is bound to a specific Activity. Therefore, it needs to be created and configured
// every time this Fragment attaches to a new Activity.
// TODO(mattcarroll): the PlatformPlugin needs to be reimagined because it implicitly takes
// control of the entire window. This is unacceptable for non-fullscreen
// use-cases.
platformPlugin = host.providePlatformPlugin(host.getActivity(), flutterEngine);
host.configureFlutterEngine(flutterEngine);
isAttached = true;
}
3.1 FlutterActivityAndFragmentDelegate---创建的FlutterEngine
public FlutterEngine(
@NonNull Context context,
@Nullable FlutterLoader flutterLoader,
@NonNull FlutterJNI flutterJNI,
@NonNull PlatformViewsController platformViewsController,
@Nullable String[] dartVmArgs,
boolean automaticallyRegisterPlugins,
boolean waitForRestorationData,
@Nullable FlutterEngineGroup group) {
AssetManager assetManager;
try {
assetManager = context.createPackageContext(context.getPackageName(), 0).getAssets();
} catch (NameNotFoundException e) {
assetManager = context.getAssets();
}
FlutterInjector injector = FlutterInjector.instance();
if (flutterJNI == null) {
flutterJNI = injector.getFlutterJNIFactory().provideFlutterJNI();
}
this.flutterJNI = flutterJNI;
this.dartExecutor = new DartExecutor(flutterJNI, assetManager);
this.dartExecutor.onAttachedToJNI();
DeferredComponentManager deferredComponentManager =
FlutterInjector.instance().deferredComponentManager();
accessibilityChannel = new AccessibilityChannel(dartExecutor, flutterJNI);
deferredComponentChannel = new DeferredComponentChannel(dartExecutor);
lifecycleChannel = new LifecycleChannel(dartExecutor);
localizationChannel = new LocalizationChannel(dartExecutor);
mouseCursorChannel = new MouseCursorChannel(dartExecutor);
navigationChannel = new NavigationChannel(dartExecutor);
platformChannel = new PlatformChannel(dartExecutor);
restorationChannel = new RestorationChannel(dartExecutor, waitForRestorationData);
settingsChannel = new SettingsChannel(dartExecutor);
spellCheckChannel = new SpellCheckChannel(dartExecutor);
systemChannel = new SystemChannel(dartExecutor);
textInputChannel = new TextInputChannel(dartExecutor);
@VisibleForTesting
/* package */ void setupFlutterEngine() {
Log.v(TAG, "Setting up FlutterEngine.");
// First, check if the host wants to use a cached FlutterEngine.
String cachedEngineId = host.getCachedEngineId();
if (cachedEngineId != null) {
flutterEngine = FlutterEngineCache.getInstance().get(cachedEngineId);
isFlutterEngineFromHost = true;
if (flutterEngine == null) {
throw new IllegalStateException(
"The requested cached FlutterEngine did not exist in the FlutterEngineCache: '"
+ cachedEngineId
+ "'");
}
return;
}
// Second, defer to subclasses for a custom FlutterEngine.
flutterEngine = host.provideFlutterEngine(host.getContext());
if (flutterEngine != null) {
isFlutterEngineFromHost = true;
return;
}
// Third, check if the host wants to use a cached FlutterEngineGroup
// and create new FlutterEngine using FlutterEngineGroup#createAndRunEngine
String cachedEngineGroupId = host.getCachedEngineGroupId();
if (cachedEngineGroupId != null) {
FlutterEngineGroup flutterEngineGroup =
FlutterEngineGroupCache.getInstance().get(cachedEngineGroupId);
if (flutterEngineGroup == null) {
throw new IllegalStateException(
"The requested cached FlutterEngineGroup did not exist in the FlutterEngineGroupCache: '"
+ cachedEngineGroupId
+ "'");
}
flutterEngine =
flutterEngineGroup.createAndRunEngine(
addEntrypointOptions(new FlutterEngineGroup.Options(host.getContext())));
isFlutterEngineFromHost = false;
return;
}
// Our host did not provide a custom FlutterEngine. Create a FlutterEngine to back our
// FlutterView.
Log.v(
TAG,
"No preferred FlutterEngine was provided. Creating a new FlutterEngine for"
+ " this FlutterFragment.");
FlutterEngineGroup group =
engineGroup == null
? new FlutterEngineGroup(host.getContext(), host.getFlutterShellArgs().toArray())
: engineGroup;
flutterEngine =
group.createAndRunEngine(
addEntrypointOptions(
new FlutterEngineGroup.Options(host.getContext())
.setAutomaticallyRegisterPlugins(false)
.setWaitForRestorationData(host.shouldRestoreAndSaveState())));
isFlutterEngineFromHost = false;
}
3.2 FlutterEngine: 引擎。(重要)
1). FlutterEngine 是一个独立的 Flutter 运行环境容器,通过它可以在 Android 应用程序中运行 Dart 代码。
使用 FlutterEngine 执行 Dart 或 Flutter 代码需要先通过 FlutterEngine 获取 DartExecutor 引用,然后调用 DartExecutor 的executeDartEntrypoint(DartExecutor.DartEntrypoint)执行 Dart 代码即可
2). FlutterEngine 中的 Dart 代码可以在后台执行,也可以使用附带的 FlutterRenderer 和 Dart 代码将 Dart 端 UI 效果渲染到屏幕上,渲染可以开始和停止,从而允许 FlutterEngine 从 UI 交互转移到仅进行数据处理,然后又返回到 UI 交互的能力v
3). 在Flutter引擎启动也初始化完成后,执行FlutterActivityDelegate.runBundle()加载Dart代码,其中entrypoint和libraryPath分别代表主函数入口的函数名”main”和所对应库的路径, 经过层层调用后开始执行dart层的main()方法,执行runApp()的过程,这便开启执行整个Dart业务代码。
四大关系: FlutterEngine,DartExecutor,Dart VM, Isloate
FlutterJNI:engine 层的 JNI 接口都在这里面注册、绑定。通过他可以调用 engine 层的 c/c++ 代码
DartExecutor:用于执行 Dart 代码(调用 DartExecutor 的executeDartEntrypoint(DartExecutor.DartEntrypoint)即可执行,一个 FlutterEngine 执行一次)
FlutterRenderer:FlutterRenderer 实例 attach 上一个 RenderSurface 也就是之前说的 FlutterView
这里 FlutterEngine 与 DartExecutor、Dart VM、Isolate 的关系大致可以归纳如下:
一个Native进程只有一个DartVM。
一个DartVM(或说一个Native进程)可以有多个FlutterEngine。
多个FlutterEngine运行在各自的Isolate中,他们的内存数据不共享,需要通过Isolate事先设置的port(顶级函数)通讯。
FlutterEngine可以后台运行代码,不渲染UI;也可以通过FlutterRender渲染UI。
图解:在platform_view_android_jni.cc的AttachJNI过程会初始化AndroidShellHolder对象,该对象初始化过程的主要工作:
- 创建AndroidShellHolder对象,会初始化ThreadHost,并创建1.ui, 1.gpu, 1.io这3个线程。每个线程Thread初始化过程,都会创建相应的MessageLoop、TaskRunner对象,然后进入pollOnce轮询等待状态;
- 创建Shell对象,设置默认log只输出ERROR级别,除非在启动的时候带上参数verbose_logging,则会打印出INFO级别的日志;
- 当进程存在正在运行DartVM,则获取其强引用,复用该DartVM,否则新创建一个Dart虚拟机;
- 在Shell::CreateShellOnPlatformThread()过程执行如下操作:
- 主线程中创建PlatformViewAndroid对象,AndroidSurfaceGL、GPUSurfaceGL以及VsyncWaiterAndroid对象;
- io线程中创建ShellIOManager对象,GrContext、SkiaUnrefQueue对象
- gpu线程中创建Rasterizer对象,CompositorContext对象
- ui线程中创建Engine、Animator对象,RuntimeController、Window对象,以及DartIsolate、Isolate对象
可见,每一个FlutterActivity都有相对应的FlutterView、AndroidShellHolder、Shell、Engine、Animator、PlatformViewAndroid、RuntimeController、Window等对象。但每一个进进程DartVM独有一份;
不错的图.jpg3.3 FlutterActivityAndFragmentDelegate---创建的view
createFlutterView
FlutterView:
View onCreateView(
LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState,
int flutterViewId,
boolean shouldDelayFirstAndroidViewDraw) {
Log.v(TAG, "Creating FlutterView.");
ensureAlive();
if (host.getRenderMode() == RenderMode.surface) {
FlutterSurfaceView flutterSurfaceView =
new FlutterSurfaceView(
host.getContext(), host.getTransparencyMode() == TransparencyMode.transparent);
// Allow our host to customize FlutterSurfaceView, if desired.
host.onFlutterSurfaceViewCreated(flutterSurfaceView);
// Create the FlutterView that owns the FlutterSurfaceView.
flutterView = new FlutterView(host.getContext(), flutterSurfaceView);
} else {
FlutterTextureView flutterTextureView = new FlutterTextureView(host.getContext());
flutterTextureView.setOpaque(host.getTransparencyMode() == TransparencyMode.opaque);
// Allow our host to customize FlutterSurfaceView, if desired.
host.onFlutterTextureViewCreated(flutterTextureView);
// Create the FlutterView that owns the FlutterTextureView.
flutterView = new FlutterView(host.getContext(), flutterTextureView);
}
// Add listener to be notified when Flutter renders its first frame.
flutterView.addOnFirstFrameRenderedListener(flutterUiDisplayListener);
Log.v(TAG, "Attaching FlutterEngine to FlutterView.");
flutterView.attachToFlutterEngine(flutterEngine); // flutter绑定 flutterEngine
flutterView.setId(flutterViewId);
SplashScreen splashScreen = host.provideSplashScreen();
return flutterView;
}
attachToFlutterEngine:这个方法里将FlutterSurfaceView的Surface提供给指定的FlutterRender,用于将Flutter UI绘制到当前的FlutterSurfaceView
FlutterNativeView
void onStart() {
Log.v(TAG, "onStart()");
ensureAlive();
doInitialFlutterViewRun();
// This is a workaround for a bug on some OnePlus phones. The visibility of the application
// window is still true after locking the screen on some OnePlus phones, and shows a black
// screen when unlocked. We can work around this by changing the visibility of FlutterView in
// onStart and onStop.
// See https://github.com/flutter/flutter/issues/93276
if (previousVisibility != null) {
flutterView.setVisibility(previousVisibility);
}
}
private void doInitialFlutterViewRun() {
// Don't attempt to start a FlutterEngine if we're using a cached FlutterEngine.
if (host.getCachedEngineId() != null) {
return;
}
if (flutterEngine.getDartExecutor().isExecutingDart()) {
// No warning is logged because this situation will happen on every config
// change if the developer does not choose to retain the Fragment instance.
// So this is expected behavior in many cases.
return;
}
String initialRoute = host.getInitialRoute();
if (initialRoute == null) {
initialRoute = maybeGetInitialRouteFromIntent(host.getActivity().getIntent());
if (initialRoute == null) {
initialRoute = DEFAULT_INITIAL_ROUTE;
}
}
@Nullable String libraryUri = host.getDartEntrypointLibraryUri();
Log.v(
TAG,
"Executing Dart entrypoint: "
+ host.getDartEntrypointFunctionName()
+ ", library uri: "
+ libraryUri
== null
? "\"\""
: libraryUri + ", and sending initial route: " + initialRoute);
// The engine needs to receive the Flutter app's initial route before executing any
// Dart code to ensure that the initial route arrives in time to be applied.
flutterEngine.getNavigationChannel().setInitialRoute(initialRoute);
String appBundlePathOverride = host.getAppBundlePath();
if (appBundlePathOverride == null || appBundlePathOverride.isEmpty()) {
appBundlePathOverride = FlutterInjector.instance().flutterLoader().findAppBundlePath();
}
// Configure the Dart entrypoint and execute it.
DartExecutor.DartEntrypoint entrypoint =
libraryUri == null
? new DartExecutor.DartEntrypoint(
appBundlePathOverride, host.getDartEntrypointFunctionName())
: new DartExecutor.DartEntrypoint(
appBundlePathOverride, libraryUri, host.getDartEntrypointFunctionName());
flutterEngine.getDartExecutor().executeDartEntrypoint(entrypoint, host.getDartEntrypointArgs());
}
DartExecutor
public void executeDartEntrypoint(
@NonNull DartEntrypoint dartEntrypoint, @Nullable List<String> dartEntrypointArgs) {
if (isApplicationRunning) {
Log.w(TAG, "Attempted to run a DartExecutor that is already running.");
return;
}
TraceSection.begin("DartExecutor#executeDartEntrypoint");
try {
Log.v(TAG, "Executing Dart entrypoint: " + dartEntrypoint);
flutterJNI.runBundleAndSnapshotFromLibrary(
dartEntrypoint.pathToBundle,
dartEntrypoint.dartEntrypointFunctionName,
dartEntrypoint.dartEntrypointLibrary,
assetManager,
dartEntrypointArgs);
isApplicationRunning = true;
} finally {
TraceSection.end();
}
}
FlutterJNI
@UiThread
public void runBundleAndSnapshotFromLibrary(
@NonNull String bundlePath,
@Nullable String entrypointFunctionName,
@Nullable String pathToEntrypointFunction,
@NonNull AssetManager assetManager,
@Nullable List<String> entrypointArgs) {
ensureRunningOnMainThread();
ensureAttachedToNative();
nativeRunBundleAndSnapshotFromLibrary(
nativeShellHolderId,
bundlePath,
entrypointFunctionName,
pathToEntrypointFunction,
assetManager,
entrypointArgs);
}
private native void nativeRunBundleAndSnapshotFromLibrary(
long nativeShellHolderId,
@NonNull String bundlePath,
@Nullable String entrypointFunctionName,
@Nullable String pathToEntrypointFunction,
@NonNull AssetManager manager,
@Nullable List<String> entrypointArgs);
AndroidShellHolder: C++
void AndroidShellHolder::Launch(std::shared_ptr<AssetManager> asset_manager,
const std::string& entrypoint,
const std::string& libraryUrl) {
...
shell_->RunEngine(std::move(config.value()));
}
Shell. : C++
Shell 的作用?
a、Shell 是 Flutter 的底层框架,它提供了一个跨平台的渲染引擎、视图系统和一套基础库。Shell 是构建 Flutter 应用程序的基础,它将应用程序逻辑和 Flutter 引擎的交互封装在一起。
b、Flutter 应用程序通常包含一个或多个 Shell,每个 Shell 包含一个渲染线程和一个 Dart 执行上下文。Shell 接收来自 Dart 代码的指令,并将其翻译成图形、动画和其他视觉效果,以及响应用户的输入事件。Shell 还提供了对 Flutter 引擎的访问,使开发者可以配置引擎和访问它的功能。
[-> flutter/shell/common/shell.cc]
void Shell::RunEngine(
RunConfiguration run_configuration,
const std::function<void(Engine::RunStatus)>& result_callback) {
...
fml::TaskRunner::RunNowOrPostTask(
task_runners_.GetUITaskRunner(), // [10]
fml::MakeCopyable(
[run_configuration = std::move(run_configuration),
weak_engine = weak_engine_, result]() mutable {
...
auto run_result = weak_engine->Run(std::move(run_configuration));
...
result(run_result);
}));
}
Engine. : C++
// ./shell/common/engine.cc
Engine::RunStatus Engine::Run(RunConfiguration configuration) {
...
last_entry_point_ = configuration.GetEntrypoint();
last_entry_point_library_ = configuration.GetEntrypointLibrary();
auto isolate_launch_status =
PrepareAndLaunchIsolate(std::move(configuration)); // [11]
...
std::shared_ptr<DartIsolate> isolate =
runtime_controller_->GetRootIsolate().lock();
bool isolate_running =
isolate && isolate->GetPhase() == DartIsolate::Phase::Running;
if (isolate_running) {
...
std::string service_id = isolate->GetServiceId();
fml::RefPtr<PlatformMessage> service_id_message =
fml::MakeRefCounted<flutter::PlatformMessage>(
kIsolateChannel, // 此处设置为IsolateChannel
std::vector<uint8_t>(service_id.begin(), service_id.end()),
nullptr);
HandlePlatformMessage(service_id_message); // [12]
}
return isolate_running ? Engine::RunStatus::Success
: Engine::RunStatus::Failure;
}
DartIsolate
[[nodiscard]] bool DartIsolate::Run(const std::string& entrypoint_name,
const std::vector<std::string>& args,
const fml::closure& on_run) {
if (phase_ != Phase::Ready) {
return false;
}
tonic::DartState::Scope scope(this);
auto user_entrypoint_function =
Dart_GetField(Dart_RootLibrary(), tonic::ToDart(entrypoint_name.c_str()));
auto entrypoint_args = tonic::ToDart(args);
if (!InvokeMainEntrypoint(user_entrypoint_function, entrypoint_args)) {
return false;
}
phase_ = Phase::Running;
if (on_run) {
on_run();
}
return true;
}
这里首先将 Isolate 的状态设置为 Running 接着调用 dart 的 main 方法。这里 InvokeMainEntrypoint 是执行 main 方法的关键
[[nodiscard]] static bool InvokeMainEntrypoint(
Dart_Handle user_entrypoint_function,
Dart_Handle args) {
...
Dart_Handle start_main_isolate_function =
tonic::DartInvokeField(Dart_LookupLibrary(tonic::ToDart("dart:isolate")),
"_getStartMainIsolateFunction", {});
...
if (tonic::LogIfError(tonic::DartInvokeField(
Dart_LookupLibrary(tonic::ToDart("dart:ui")), "_runMainZoned",
{start_main_isolate_function, user_entrypoint_function, args}))) {
return false;
}
return true;
}
问题: Dart中编写的Widget最终是如何绘制到平台View上的呢???
PlatformView:
为了能让一些现有的 native 控件直接引用到 Flutter app 中,Flutter 团队提供了 AndroidView 、UIKitView 两个 widget 来满足需求
platform view 就是 AndroidView 和 UIKitView 的总称
问题:FlutterActivity 这些 Java 类是属于哪一层呢?是 framework 还是 engine 亦或是 platform 呢
4.4个线程比较
1). Platform Task Runner (或者叫 Platform Thread)的功能是要处理平台(android/iOS)的消息。举个简单的例子,我们 MethodChannel 的回调方法 onMethodCall 就是在这个线程上
2). UI Task Runner用于执行Root Isolate代码,它运行在线程对应平台的线程上,属于子线程。同时,Root isolate在引擎启动时会绑定了不少Flutter需要的函数方法,以便进行渲染操作。
3). GPU Task Runner主要用于执行设备GPU的指令。在UI Task Runner 创建layer tree,在GPU Task Runner将Layer Tree提供的信息转化为平台可执行的GPU指令。除了将Layer Tree提供的信息转化为平台可执行的GPU指令,GPU Task Runner同时也负责管理每一帧绘制所需要的GPU资源,包括平台Framebuffer的创建,Surface生命周期管理,以及Texture和Buffers的绘制时机等
4). IO Task Runner也运行在平台对应的子线程中,主要作用是做一些预先处理的读取操作,为GPU Runner的渲染操作做准备。我们可以认为IO Task Runner是GPU Task Runner的助手,它可以减少GPU Task Runner的额外工作。例如,在Texture的准备过程中,IO Runner首先会读取压缩的图片二进制数据,并将其解压转换成GPU能够处理的格式,然后再将数据传递给GPU进行渲染。
5.flutter入库的启动逻辑
三行代码代表了Flutter APP 启动的三个主流程:
binding初始化(ensureInitialized)
创建根 widget,绑定根节点(scheduleAttachRootWidget)
绘制热身帧(scheduleWarmUpFrame)
void runApp(Widget app) {
WidgetsFlutterBinding.ensureInitialized()
..scheduleAttachRootWidget(app)
..scheduleWarmUpFrame();
}
网友评论