目錄
1.Flutter的3層架構
2.android開始啟動flutter源碼分析
3.核心類分析
). FlutterActivityAndFragmentDelegate
). FlutterEngine
).FlutterView
). FlutterEngine
).DartExecutor
4.4個線程比較
5.flutter入庫的啟動邏輯
1.Flutter架構的核心架構
Flutter的架構原理
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
架構圖如下:
class 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獨有一份;
3.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();
}