Flutter深入之flutter初始化

Flutter深入之flutter初始化

开篇

前面两篇我们讲到了Flutter应用如何编译,并将编译结果如何放入APK中。那么当应用启动时,又是如何执行到main.dart中的main方法呢?Flutter的绘制内容又是如何被显示的呢?

flutter-启动流程

FlutterApplication

在应用启动的Application中会执行一些初始化操作,比如初始化一些路径文件夹等配置,搬移flutter资源,最为重要的是安装flutter.so。在前面的编译讲解中,我们知道该so就是flutter-engine。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# FlutterMain.java
public static void startInitialization(Context applicationContext, Settings settings) {
...
sSettings = settings;
long initStartTimestampMillis = SystemClock.uptimeMillis();
// 初始化路径等配置
initConfig(applicationContext);
// 检测aot
initAot(applicationContext);
// 搬移flutter资源
initResources(applicationContext);
// 加载so
System.loadLibrary("flutter");

// initTimeMicros是java层初始化loadLibrary所花费的时间。
// 因为so库中需要记录flutter开始的时间,但是在加载so库之前,
// 是无法调用so中的api,所以将加载so库所花费的时间传下去,然后so库中使用当前时间回退该花费时间,就是应用启动的真正时间。
long initTimeMillis = SystemClock.uptimeMillis() - initStartTimestampMillis;
nativeRecordStartTimestamp(initTimeMillis);
}
1
2
3
4
5
6
7
8
9
# flutter_main.cc
static void RecordStartTimestamp(JNIEnv* env,
jclass jcaller,
jlong initTimeMillis) {
int64_t initTimeMicros =
static_cast<int64_t>(initTimeMillis) * static_cast<int64_t>(1000);
// initTimeMicros是java层初始化所花费的时间,使用当前时间回退该花费时间,就是应用启动的真正时间。
blink::engine_main_enter_ts = Dart_TimelineGetMicros() - initTimeMicros;
}

在加载so库完成后,会触发JNI回调JNI_OnLoad,开始动态注册JNI方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# library_loader.cc
JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
// 将javaVM保存成全局变量
fml::jni::InitJavaVM(vm);
// 获取JNIEnv,通过JNIEnv.RegisterNatives来动态注册
JNIEnv* env = fml::jni::AttachCurrentThread();
bool result = false;

// 注册FlutterMain.java中的native方法
result = shell::FlutterMain::Register(env);
FML_CHECK(result);

// 注册FlutterCallbackInformation.java、FlutterView.java、FlutterNativeView.java中的native方法
result = shell::PlatformViewAndroid::Register(env);
FML_CHECK(result);

// 注册VsyncWaiter.java中的native方法
result = shell::VsyncWaiterAndroid::Register(env);
FML_CHECK(result);

return JNI_VERSION_1_4;
}

FlutterActivity

一个Flutter应用是依附在一个Android的View上的,也就是FlutterView,而FlutterActivity会将FlutterView添加到自己的布局上。

FlutterView是一个SurfaceView

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# FlutterActivityDelegate.java
@Override
public void onCreate(Bundle savedInstanceState) {
// 通过flutter run启动时,是通过 shell am start 来启动,在启动时候会设置一些参数,这些参数会放入到Activity的intent中
String[] args = getArgsFromIntent(activity.getIntent());
// 调用JNI方法nativeInit去初始化
FlutterMain.ensureInitializationComplete(activity.getApplicationContext(), args);
// 默认为null,可以在Activity中重写createFlutterView方法,实现自己的FlutterView
flutterView = viewFactory.createFlutterView(activity);
if (flutterView == null) {
// 默认为null,可以在Activity中重写createFlutterNativeView方法,实现自己的FlutterNativeView
FlutterNativeView nativeView = viewFactory.createFlutterNativeView();
// 创建FlutterView
flutterView = new FlutterView(activity, null, nativeView);
flutterView.setLayoutParams(matchParent);
// 将FlutterView放入Activity中
activity.setContentView(flutterView);
// 创建一个view,背景色设置为windowBackground中的颜色,作为Flutter项目启动之前的视图
launchView = createLaunchView();
if (launchView != null) {
// 添加到Activity中,
// 并设置FirstFrameListener监听,当Surface创建完成时,移除这个view
addLaunchView();
}
}
// 如果是通过flutter run启动的,则从intent中解析bundle参数,直接运行
if (loadIntent(activity.getIntent())) {
return;
}
if (!flutterView.getFlutterNativeView().isApplicationRunning()) {
// 获取flutter项目地址,默认是flutter_assets目录
String appBundlePath = FlutterMain.findAppBundlePath(activity.getApplicationContext());
if (appBundlePath != null) {
FlutterRunArguments arguments = new FlutterRunArguments();
arguments.bundlePath = appBundlePath;
arguments.entrypoint = "main";
// 运行flutter项目
flutterView.runFromBundle(arguments);
}
}
}
nativeInit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# flutter_main.cc
void FlutterMain::Init(JNIEnv* env,
jclass clazz,
jobject context,
jobjectArray jargs,
jstring bundlePath,
jstring appStoragePath,
jstring engineCachesPath) {
// 处理启动命令参数
auto command_line = fml::CommandLineFromIterators(args.begin(), args.end());

auto settings = SettingsFromCommandLine(command_line);
// 默认是flutter_assets目录,可以通过在manifest中meta里面使用PUBLIC_FLUTTER_ASSETS_DIR_KEY来设置
settings.assets_path = fml::jni::JavaStringToString(env, bundlePath);
...
// 如果是debug模式
if (!blink::DartVM::IsRunningPrecompiledCode()) {
// kernel_blob.bin文件就是dart工程编译后生成的二进制文件
auto application_kernel_path =
fml::paths::JoinPaths({settings.assets_path, "kernel_blob.bin"});
if (fml::IsFile(application_kernel_path)) {
settings.application_kernel_asset = application_kernel_path;
}
}
...
// 创建FlutterMain
g_flutter_main.reset(new FlutterMain(std::move(settings)));
}
创建FlutterView

FlutterView与Flutter代码进行通信则是通过FlutterNativeView来进行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# FlutterView.java    
public FlutterView(Context context, AttributeSet attrs, FlutterNativeView nativeView) {
super(context, attrs);
// 是否使用skia渲染,只有在模拟器上并且开启了才会使用,默认情况下,在真机上会优先使用OpenGL或者Vulkan
// 在flutter run时可以加上参数--enable-software-rendering来开启
mIsSoftwareRenderingEnabled = nativeGetIsSoftwareRenderingEnabled();
// 监听系统级别的Activity过渡动画属性是否开启,随时改变
mAnimationScaleObserver = new AnimationScaleObserver(new Handler());
mMetrics = new ViewportMetrics();
mMetrics.devicePixelRatio = context.getResources().getDisplayMetrics().density;
setFocusable(true);
setFocusableInTouchMode(true);

Activity activity = (Activity) getContext();
if (nativeView == null) {
// 创建默认的FlutterNativeView
mNativeView = new FlutterNativeView(activity.getApplicationContext());
} else {
mNativeView = nativeView;
}
// 在PlatformViewsController中注册了一个MethodChannel插件,名字为flutter/platform_views
mNativeView.attachViewAndActivity(this, activity);

mSurfaceCallback = new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
assertAttached();
// 通知native层 surface创建
// mNativeView.get()得到的就是nativeAttach返回的AndroidShellHolder对象指针
nativeSurfaceCreated(mNativeView.get(), holder.getSurface());
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
assertAttached();
// 通知native层 surface改变,需重新创建
nativeSurfaceChanged(mNativeView.get(), width, height);
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
assertAttached();
// 通知native层 surface销毁
nativeSurfaceDestroyed(mNativeView.get());
}
};
getHolder().addCallback(mSurfaceCallback);

mAccessibilityManager = (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);

mActivityLifecycleListeners = new ArrayList<>();
mFirstFrameListeners = new ArrayList<>();

// 创建各种插件调用,这些插件已经在engine.cc中和system_channels.dart实现,
// 通过这些插件,可以调用Flutter Engine中的指定方法
mFlutterLocalizationChannel = new MethodChannel(this, "flutter/localization", JSONMethodCodec.INSTANCE);
mFlutterNavigationChannel = new MethodChannel(this, "flutter/navigation", JSONMethodCodec.INSTANCE);
mFlutterKeyEventChannel = new BasicMessageChannel<>(this, "flutter/keyevent", JSONMessageCodec.INSTANCE);
mFlutterLifecycleChannel = new BasicMessageChannel<>(this, "flutter/lifecycle", StringCodec.INSTANCE);
mFlutterSystemChannel = new BasicMessageChannel<>(this, "flutter/system", JSONMessageCodec.INSTANCE);
mFlutterSettingsChannel = new BasicMessageChannel<>(this, "flutter/settings", JSONMessageCodec.INSTANCE);
// 创建插件flutter/platform,提供给dart中使用
PlatformPlugin platformPlugin = new PlatformPlugin(activity);
MethodChannel flutterPlatformChannel = new MethodChannel(this, "flutter/platform", JSONMethodCodec.INSTANCE);
flutterPlatformChannel.setMethodCallHandler(platformPlugin);
addActivityLifecycleListener(platformPlugin);
mImm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
mTextInputPlugin = new TextInputPlugin(this);
// 将当前的locale信息设置给dart
setLocale(getResources().getConfiguration().locale);
// 将系统字体缩放和时间格式设置给dart
setUserSettings();
}
nativeSurfaceCreated
1
2
3
4
5
6
7
8
9
10
static void SurfaceCreated(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jobject jsurface) {
fml::jni::ScopedJavaLocalFrame scoped_local_reference_frame(env);
// 通过ndk获取Android中surface对象对应的NativeWindow对象,将其放入AndroidNativeWindow中维护。
auto window = fml::MakeRefCounted<AndroidNativeWindow>(
ANativeWindow_fromSurface(env, jsurface));
ANDROID_SHELL_HOLDER->GetPlatformView()->NotifyCreated(std::move(window));
}
1
2
3
4
5
6
7
8
9
10
11
void PlatformViewAndroid::NotifyCreated(
fml::RefPtr<AndroidNativeWindow> native_window) {
if (android_surface_) {
// 通过jni调用上层FlutterNativeView.onFirstFrame方法,执行上层注册的FirstFrameListener;
InstallFirstFrameCallback();
// 给AndroidSurface设置window
// 比如AndroidSurfaceGL实现就会通过eglCreateWindowSurface来创建一个基于该window的surface
android_surface_->SetNativeWindow(native_window);
}
PlatformView::NotifyCreated();
}
nativeSurfaceChanged
1
2
3
4
5
6
7
8
static void SurfaceChanged(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jint width,
jint height) {
ANDROID_SHELL_HOLDER->GetPlatformView()->NotifyChanged(
SkISize::Make(width, height));
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void PlatformViewAndroid::NotifyChanged(const SkISize& size) {
if (!android_surface_) {
return;
}
fml::AutoResetWaitableEvent latch;
fml::TaskRunner::RunNowOrPostTask(
task_runners_.GetGPUTaskRunner(), //
// 在GPU线程中执行,通知AndroidSurface对象去重新创建Surface
// 比如AndroidSurfaceGL就会
// 先通过eglMakeCurrent EGL_NO_SURFACE 来解除绑定
// 再通过eglDestroySurface销毁当前surface,
// 然后再调用eglCreateWindowSurface重新创建一个surface
[&latch, surface = android_surface_.get(), size]() {
surface->OnScreenSurfaceResize(size);
latch.Signal();
});
latch.Wait();
}
nativeSurfaceDestroyed
1
2
3
static void SurfaceDestroyed(JNIEnv* env, jobject jcaller, jlong shell_holder) {
ANDROID_SHELL_HOLDER->GetPlatformView()->NotifyDestroyed();
}
1
2
3
4
5
6
7
8
9
void PlatformViewAndroid::NotifyDestroyed() {
PlatformView::NotifyDestroyed();
if (android_surface_) {
// 直接在当前线程通知AndroidSurface销毁Surface
// 比如AndroidSurfaceGL
// 会调用eglMakeCurrent EGL_NO_SURFACE 来解除绑定
android_surface_->TeardownOnScreenContext();
}
}
创建FlutterNativeView

FlutterNativeView是一个与Flutter异步通信的工具,在FlutterNativeView创建的时候,通过nativeAttach将对象实例传给native层。

具体通信就是FlutterNativeView通过jni与c++通信,然后c++通过其封装的Tonic库调用dart代码;dart代码通过native方法与c++通信,然后c++通过attach中传入的Java对象实例,以及JNIEnv对象,调用Java对象的方法。从而实现了Java与Dart的互相调用。

nativeAttacch
1
2
3
4
5
6
7
8
9
# FlutterNativeView.java
public FlutterNativeView(Context context, boolean isBackgroundView) {
mContext = context;
// 用来注册plugin
mPluginRegistry = new FlutterPluginRegistry(this, context);
attach(this, isBackgroundView);
assertAttached();
mMessageHandlers = new HashMap<>();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# platform_view_android_jni.cc
static jlong Attach(JNIEnv* env,
jclass clazz,
jobject flutterView,
jboolean is_background_view) {
// 使用FlutterNativeView实例引用创建一个全局弱引用保存
fml::jni::JavaObjectWeakGlobalRef java_object(env, flutterView);
// 创建AndroidShellHolder对象,并返回其指针
auto shell_holder = std::make_unique<AndroidShellHolder>(
FlutterMain::Get().GetSettings(), java_object, is_background_view);
if (shell_holder->IsValid()) {
return reinterpret_cast<jlong>(shell_holder.release());
} else {
return 0;
}
}
创建AndroidShellHolder

在engine中有四种线程,分别是paltform、ui、gpu、io。其中会把当前初始化的线程作为platform线程,并维护一个当前线程的Android Loop对象。每一个线程对象中都有一个TaskRunner对象,用来执行操作任务。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# android_shell_holder.cc
AndroidShellHolder::AndroidShellHolder(
blink::Settings settings,
fml::jni::JavaObjectWeakGlobalRef java_object,
bool is_background_view)
: settings_(std::move(settings)), java_object_(java_object) {
...
if (is_background_view) {
// 如果是后台视图,则只创建ui线程
thread_host_ = {thread_label, ThreadHost::Type::UI};
} else {
// 默认创建的FlutterNativeView,is_background_view = false
// 则创建ui线程,gpu线程,io线程
thread_host_ = {thread_label, ThreadHost::Type::UI | ThreadHost::Type::GPU |
ThreadHost::Type::IO};
}
...
fml::WeakPtr<PlatformViewAndroid> weak_platform_view;
// 通过模板函数一个回调,在回调中创建PlatFormViewAndroid
Shell::CreateCallback<PlatformView> on_create_platform_view =
[is_background_view, java_object, &weak_platform_view](Shell& shell) {
// 创建PlatformViewAndroid
std::unique_ptr<PlatformViewAndroid> platform_view_android;
// 如果是后台视图,则一定不使用软件渲染;否则就看配置中是否开启
if (is_background_view) {
platform_view_android = std::make_unique<PlatformViewAndroid>(
shell, // delegate
shell.GetTaskRunners(), // task runners
java_object // java object handle for JNI interop
);
} else {
platform_view_android = std::make_unique<PlatformViewAndroid>(
shell, // delegate
shell.GetTaskRunners(), // task runners
java_object, // java object handle for JNI interop
shell.GetSettings()
.enable_software_rendering // use software rendering
);
}
weak_platform_view = platform_view_android->GetWeakPtr();
return platform_view_android;
};
// 通过模板函数创建一个回调,在回调中创建Rasterizer
Shell::CreateCallback<Rasterizer> on_create_rasterizer = [](Shell& shell) {
return std::make_unique<Rasterizer>(shell.GetTaskRunners());
};
// 创建当前线程的messageLoop,并创建一个taskRunner
// 在MessageLoop和TaskRunner中都维护了一个Loop对象,该对象是根据平台来获取。对于Android来说,则是通过ndk从Android系统中获取当前线程中的Android Loop对象。如果当前线程不是主线程,没有初始化loop,则会通过ndk为当前线程创建一个loop,返回新创建的loop。
fml::MessageLoop::EnsureInitializedForCurrentThread();
fml::RefPtr<fml::TaskRunner> gpu_runner;
fml::RefPtr<fml::TaskRunner> ui_runner;
fml::RefPtr<fml::TaskRunner> io_runner;
// 上面创建的taskRunner作为paltform_runner,所以platform_runner中维护的是Android当前线程的loop对象。
fml::RefPtr<fml::TaskRunner> platform_runner =
fml::MessageLoop::GetCurrent().GetTaskRunner();
if (is_background_view) {
// 如果是后台视图,则只有一个ui线程,所以四大TaskRunner都等于UITaskRunner
auto single_task_runner = thread_host_.ui_thread->GetTaskRunner();
gpu_runner = single_task_runner;
ui_runner = single_task_runner;
io_runner = single_task_runner;
} else {
// 拿到其它三个线程的三个TaskRunner
gpu_runner = thread_host_.gpu_thread->GetTaskRunner();
ui_runner = thread_host_.ui_thread->GetTaskRunner();
io_runner = thread_host_.io_thread->GetTaskRunner();
}
// 使用四大TaskRunner创建TaskRunners对象
blink::TaskRunners task_runners(thread_label, // label
platform_runner, // platform
gpu_runner, // gpu
ui_runner, // ui
io_runner // io
);
// 创建Shell对象
shell_ =
Shell::Create(task_runners, // task runners
settings_, // settings
on_create_platform_view, // platform view create callback
on_create_rasterizer // rasterizer create callback
);

platform_view_ = weak_platform_view;
FML_DCHECK(platform_view_);

is_valid_ = shell_ != nullptr;

if (is_valid_) {
task_runners.GetGPUTaskRunner()->PostTask([]() {
// 在Android中线程优先级-8是最高级别的,所以GPU线程的级别稍微低一点,设为-5
// 详情请看 Proces.THREAD_PRIORITY_URGENT_DISPLAY
if (::setpriority(PRIO_PROCESS, gettid(), -5) != 0) {
// 如果失败,则改成-2
if (::setpriority(PRIO_PROCESS, gettid(), -2) != 0) {
FML_LOG(ERROR) << "Failed to set GPU task runner priority";
}
}
});
task_runners.GetUITaskRunner()->PostTask([]() {
// 将UI线程的优先级设为-1
if (::setpriority(PRIO_PROCESS, gettid(), -1) != 0) {
FML_LOG(ERROR) << "Failed to set UI task runner priority";
}
});
}
}
创建Shell
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# shell.cc
std::unique_ptr<Shell> Shell::Create(
blink::TaskRunners task_runners,
blink::Settings settings,
Shell::CreateCallback<PlatformView> on_create_platform_view,
Shell::CreateCallback<Rasterizer> on_create_rasterizer) {
// 初始化Skia库、初始化ICU库
PerformInitializationTasks(settings);
// 创建DartVM
auto vm = blink::DartVM::ForProcess(settings);
FML_CHECK(vm) << "Must be able to initialize the VM.";
// 在platform线程中创建Shell
return Shell::Create(std::move(task_runners), //
std::move(settings), //
vm->GetIsolateSnapshot(), //
blink::DartSnapshot::Empty(), //
std::move(on_create_platform_view), //
std::move(on_create_rasterizer) //
);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# shell.cc
std::unique_ptr<Shell> Shell::CreateShellOnPlatformThread(
blink::TaskRunners task_runners,
blink::Settings settings,
fml::RefPtr<blink::DartSnapshot> isolate_snapshot,
fml::RefPtr<blink::DartSnapshot> shared_snapshot,
Shell::CreateCallback<PlatformView> on_create_platform_view,
Shell::CreateCallback<Rasterizer> on_create_rasterizer) {
if (!task_runners.IsValid()) {
return nullptr;
}
// 创建Shell对象,并安装提供的服务的协议处理
// _flutter.screenshot 、 _flutter.screenshotSkp 、_flutter.runInView
// _flutter.flushUIThreadTasks 、 _flutter.setAssetBundlePath
auto shell = std::unique_ptr<Shell>(new Shell(task_runners, settings));

// 在platform线程创建PlatformView
// 执行回调,创建PlatFormViewAndroid对象,因为各个平台不同,所以使用回调来创建不同对象
auto platform_view = on_create_platform_view(*shell.get());

// 创建一个垂直同步工具,在Android层进行doFrame时,执行动画等操作。
// 具体实现是在c++层,调用该工具的AwaitVSync方法,
// 会通过jni调用上层VsyncWaiter.asyncWaitForVsync方法,
// 该方法会添加一个回调Choreographer.getInstance().postFrameCallback();
// 在回调doFrame时,会执行nativeOnVsync方法,执行该同步工具的OnNativeVsync方法
auto vsync_waiter = platform_view->CreateVSyncWaiter();
if (!vsync_waiter) {
return nullptr;
}

// 在IO线程创建一个IOManager
auto io_task_runner = shell->GetTaskRunners().GetIOTaskRunner();
fml::TaskRunner::RunNowOrPostTask(
io_task_runner,
...
() {
io_manager = std::make_unique<IOManager>(
platform_view->CreateResourceContext(), io_task_runner);
...
});

// 在GPU线程创建一个Rasterizer
fml::TaskRunner::RunNowOrPostTask(
task_runners.GetGPUTaskRunner(), ...() {
// 执行回调,创建Rasterizer对象
if (auto new_rasterizer = on_create_rasterizer(*shell)) {
rasterizer = std::move(new_rasterizer);
}
});

// 在UI线程中创建Engine
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetUITaskRunner(),
fml::MakeCopyable(...() mutable {
const auto& task_runners = shell->GetTaskRunners();

// 创建animator,并持有上面创建的垂直同步工具
auto animator = std::make_unique<Animator>(*shell, task_runners,
std::move(vsync_waiter));
// 创建engine
engine = std::make_unique<Engine>(*shell, //
shell->GetDartVM(), //
std::move(isolate_snapshot), //
std::move(shared_snapshot), //
task_runners, //
shell->GetSettings(), //
std::move(animator), //
std::move(resource_context), //
std::move(unref_queue) //
);
}));

// 启动
if (!shell->Setup(std::move(platform_view), //
std::move(engine), //
std::move(rasterizer), //
std::move(io_manager)) //
) {
return nullptr;
}

return shell;
}
创建DartVM
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
fml::RefPtr<DartVM> DartVM::ForProcess(
Settings settings,
fml::RefPtr<DartSnapshot> vm_snapshot,
fml::RefPtr<DartSnapshot> isolate_snapshot,
fml::RefPtr<DartSnapshot> shared_snapshot) {
std::lock_guard<std::mutex> lock(gVMMutex);
std::call_once(gVMInitialization, [settings, //
vm_snapshot, //
isolate_snapshot, //
shared_snapshot //
]() mutable {
if (!vm_snapshot) {
// 加载vm_snapshot_instr文件和vm_snapshot_data文件,创建DartSnapshot对象
vm_snapshot = DartSnapshot::VMSnapshotFromSettings(settings);
}
if (!(vm_snapshot && vm_snapshot->IsValid())) {
FML_LOG(ERROR) << "VM snapshot must be valid.";
return;
}
if (!isolate_snapshot) {
// 加载isolate_snapshot_data和isolate_snapshot_instr,创建DartSnapshot对象
isolate_snapshot = DartSnapshot::IsolateSnapshotFromSettings(settings);
}
if (!(isolate_snapshot && isolate_snapshot->IsValid())) {
FML_LOG(ERROR) << "Isolate snapshot must be valid.";
return;
}
if (!shared_snapshot) {
// 使用空文件创建一个DartSnapshot对象
shared_snapshot = DartSnapshot::Empty();
}
// 创建DartVM
gVM = fml::MakeRefCounted<DartVM>(settings, //
std::move(vm_snapshot), //
std::move(isolate_snapshot), //
std::move(shared_snapshot) //
);
});
return gVM;
}
创建AndroidSurface

在创建PatformViewANdroid的时候,会根据use_software_rendering来创建AndroidSurface来处理真正的绘制

1
2
3
4
5
6
7
8
9
10
11
12
PlatformViewAndroid::PlatformViewAndroid(
PlatformView::Delegate& delegate,
blink::TaskRunners task_runners,
fml::jni::JavaObjectWeakGlobalRef java_object,
bool use_software_rendering)
: PlatformView(delegate, std::move(task_runners)),
java_object_(java_object),
android_surface_(AndroidSurface::Create(use_software_rendering)) {
FML_CHECK(android_surface_)
<< "Could not create an OpenGL, Vulkan or Software surface to setup "
"rendering.";
}

如果use_software_rendering=true,则说明开启软件渲染,则会创建AndroidSurfaceSoftware对象,该对象中使用skia库来绘制。而如果没有开启,则如果系统支持valkan,则就创建AndroidSurfaceVulkan,如果不支持则只能使用AndroidSurfaceGL。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

std::unique_ptr<AndroidSurface> AndroidSurface::Create(
bool use_software_rendering) {
if (use_software_rendering) {
auto software_surface = std::make_unique<AndroidSurfaceSoftware>();
return software_surface->IsValid() ? std::move(software_surface) : nullptr;
}
#if SHELL_ENABLE_VULKAN
auto vulkan_surface = std::make_unique<AndroidSurfaceVulkan>();
return vulkan_surface->IsValid() ? std::move(vulkan_surface) : nullptr;
#else // SHELL_ENABLE_VULKAN
auto gl_surface = std::make_unique<AndroidSurfaceGL>();
return gl_surface->IsOffscreenContextValid() ? std::move(gl_surface)
: nullptr;
#endif // SHELL_ENABLE_VULKAN
}
启动Bundle
nativeRunBundleAndSnapshotFromLibrary
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# platform_view_android_jni.cc
static void RunBundleAndSnapshotFromLibrary(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jstring jbundlepath,
jstring jdefaultPath,
jstring jEntrypoint,
jstring jLibraryUrl,
jobject jAssetManager) {
auto asset_manager = fml::MakeRefCounted<blink::AssetManager>();
// flutter代码目录,默认是flutter_assets
const auto bundlepath = fml::jni::JavaStringToString(env, jbundlepath);
if (bundlepath.size() > 0) {
const auto file_ext_index = bundlepath.rfind(".");
if (bundlepath.substr(file_ext_index) == ".zip") {
// 如果路径是个zip文件,创建一个ZipAssetStore对象
asset_manager->PushBack(
std::make_unique<blink::ZipAssetStore>(bundlepath));
} else {
// 如果路径是个目录,创建一个DirectoryAssetBundle对象
asset_manager->PushBack(
std::make_unique<blink::DirectoryAssetBundle>(fml::OpenDirectory(
bundlepath.c_str(), false, fml::FilePermission::kRead)));
}

// 从该路径推到出APK的Assets路径
const auto last_slash_index = bundlepath.rfind("/", bundlepath.size());
if (last_slash_index != std::string::npos) {
auto apk_asset_dir = bundlepath.substr(
last_slash_index + 1, bundlepath.size() - last_slash_index);
// 创建一个APKAssetProvider对象
asset_manager->PushBack(std::make_unique<blink::APKAssetProvider>(
env, // jni environment
jAssetManager, // asset manager
std::move(apk_asset_dir)) // apk asset dir
);
}
}

...
auto isolate_configuration = CreateIsolateConfiguration(*asset_manager);
...

RunConfiguration config(std::move(isolate_configuration),
std::move(asset_manager));

{
auto entrypoint = fml::jni::JavaStringToString(env, jEntrypoint);
auto libraryUrl = fml::jni::JavaStringToString(env, jLibraryUrl);

if ((entrypoint.size() > 0) && (libraryUrl.size() > 0)) {
config.SetEntrypointAndLibrary(std::move(entrypoint),
std::move(libraryUrl));
} else if (entrypoint.size() > 0) {
// 设置进入点,默认为main
config.SetEntrypoint(std::move(entrypoint));
}
}
// 启动
ANDROID_SHELL_HOLDER->Launch(std::move(config));
}
Launch

最终调用dart运行时来加载dart代码,然后通过Tonic库来执行dart代码中的entrypoint方法,也就是main方法

1
2
3
4
5
6
7
8
9
10
11
12
void AndroidShellHolder::Launch(RunConfiguration config) {
shell_->GetTaskRunners().GetUITaskRunner()->PostTask(
fml::MakeCopyable([engine = shell_->GetEngine(), //
config = std::move(config) //
]() mutable {
// 真正是在UI线程中启动
if (!engine || engine->Run(std::move(config)) ==
shell::Engine::RunStatus::Failure) {
} else {
}
}));
}
main方法执行

最终在main方法中通过runApp来进行视图绘制显示。

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×