FlutterView
- 继承SurfaceView,它的内部有两个线程即主线程和渲染线程,使用渲染线程中向屏幕上绘图可以避免主线程阻塞,从而提高了程序的反应速度。使用了双缓冲机制。
- 实现BinaryMesaenger接口, 这个接口定义了Android代码和Flutter代码直接通信的方式,此接口还有2个内部接口。 FlutterView实现了这个接口,拥有了和flutter通信的的能力
- 实现TextureRegistry接口,这个接口主要是创建一个SurfaceTexture对象,使用SurfaceTextureEntry包装起来,拥有唯一的ID。
- 实现onAccessibilityChanged接口,主要用来监听系统accessibility 状态变化的。
-
创建一大堆Channel用于Android和flutter通信
navigationChannel = new NavigationChannel(dartExecutor); keyEventChannel = new KeyEventChannel(dartExecutor); lifecycleChannel = new LifecycleChannel(dartExecutor); localizationChannel = new LocalizationChannel(dartExecutor); platformChannel = new PlatformChannel(dartExecutor); systemChannel = new SystemChannel(dartExecutor); settingsChannel = new SettingsChannel(dartExecutor);
-
创建FlutterNativeView
//初始化 mNativeView = new FlutterNativeView(activity.getApplicationContext()); OnAccessibilityChangeListener AccessibilityStateChangeListener
-
创建一堆成员变量
mIsSoftwareRenderingEnabled 硬件加速渲染相关的
dartExecutor = mNativeView.getDartExecutor(); flutterRenderer = new FlutterRenderer(mNativeView.getFlutterJNI()); mIsSoftwareRenderingEnabled = mNativeView.getFlutterJNI().nativeGetIsSoftwareRenderingEnabled(); mMetrics = new ViewportMetrics(); mMetrics.devicePixelRatio = context.getResources().getDisplayMetrics().density; setFocusable(true); setFocusableInTouchMode(true); //attach到当前Activity mNativeView.attachViewAndActivity(this, activity); mSurfaceCallback = new SurfaceHolder.Callback() { @Override public void surfaceCreated(SurfaceHolder holder) { assertAttached(); mNativeView.getFlutterJNI().onSurfaceCreated(holder.getSurface()); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { assertAttached(); mNativeView.getFlutterJNI().onSurfaceChanged(width, height); } @Override public void surfaceDestroyed(SurfaceHolder holder) { assertAttached(); mNativeView.getFlutterJNI().onSurfaceDestroyed(); } };
FlutterNativeView
- 创建
if (nativeView == null) {
mNativeView = new FlutterNativeView(activity.getApplicationContext());
} else {
mNativeView = nativeView;
}
public FlutterNativeView(@NonNull Context context, boolean isBackgroundView) {
mContext = context;
mPluginRegistry = new FlutterPluginRegistry(this, context);
mFlutterJNI = new FlutterJNI();
mFlutterJNI.addIsDisplayingFlutterUiListener(flutterUiDisplayListener);
this.dartExecutor = new DartExecutor(mFlutterJNI, context.getAssets());
mFlutterJNI.addEngineLifecycleListener(new EngineLifecycleListenerImpl());
attach(this, isBackgroundView);
assertAttached();
}
- FlutterPluginRegistry是actitiy和flutterView绑定关系操作类,而FlutterJNI创建时,将绑定绘制、跨平台通讯、生命周期的监听方法。
- mFlutterJNI ,Engine层c++方法的一个封装类。所有Flutter JNI的调用都集合在这个类中。 一个FlutterJNI对象是和一个Platform View相关联,所以包含一个nativePlatformViewId来标识
attach(this, isBackgroundView);
private void attach(FlutterNativeView view, boolean isBackgroundView) {
mFlutterJNI.attachToNative(isBackgroundView);
dartExecutor.onAttachedToJNI();
}
public void attachToNative(boolean isBackgroundView) {
ensureRunningOnMainThread();
ensureNotAttachedToNative();
nativePlatformViewId = nativeAttach(this, isBackgroundView);
}
总结
- FlutterView提供了SurfaceView来绘制Flutter的UI
- 同时把Android的生命周期、点击事件等信息发送给Flutter。
- FlutterView并不负责直接和Flutter Engine通信,具体的通信功能在FlutterNativeView
- FlutterNativeView内部有一个FlutterJNI,它负责调用Flutter Engine的C++代码。
java到c++调用
public void attachToNative(boolean isBackgroundView) {
ensureRunningOnMainThread();
ensureNotAttachedToNative();
nativePlatformViewId = nativeAttach(this, isBackgroundView);
}
//nativeAttach对应
bool RegisterApi(JNIEnv* env) {
static const JNINativeMethod flutter_jni_methods[] = {
// Start of methods from FlutterJNI
{
.name = "nativeAttach",
.signature = "(Lio/flutter/embedding/engine/FlutterJNI;Z)J",
.fnPtr = reinterpret_cast(&AttachJNI),
},
//对应到AttachJNI
static jlong AttachJNI(JNIEnv* env,
jclass clazz,
jobject flutterJNI,
jboolean is_background_view) {
fml::jni::JavaObjectWeakGlobalRef java_object(env, flutterJNI);
std::shared_ptr jni_facade =
std::make_shared(java_object);
auto shell_holder = std::make_unique(
FlutterMain::Get().GetSettings(), jni_facade, is_background_view);
if (shell_holder->IsValid()) {
return reinterpret_cast(shell_holder.release());
} else {
return 0;
}
}
//创建auto shell_holder = std::make_unique
//对应flutter/shell/platform/android/android_shell_holder.cc
AndroidShellHolder::AndroidShellHolder创建对象
engine初始化
AndroidShellHolder::AndroidShellHolder(
flutter::Settings settings,
std::shared_ptr jni_facade,
bool is_background_view)
: settings_(std::move(settings)), jni_facade_(jni_facade) {
static size_t shell_count = 1;
auto thread_label = std::to_string(shell_count++);
FML_CHECK(pthread_key_create(&thread_destruct_key_, ThreadDestructCallback) ==
0);
if (is_background_view) {
thread_host_ = {thread_label, ThreadHost::Type::UI};
} else {
thread_host_ = {thread_label, ThreadHost::Type::UI | ThreadHost::Type::GPU |
ThreadHost::Type::IO};
}
// Detach from JNI when the UI and raster threads exit.
auto jni_exit_task([key = thread_destruct_key_]() {
FML_CHECK(pthread_setspecific(key, reinterpret_cast(1)) == 0);
});
thread_host_.ui_thread->GetTaskRunner()->PostTask(jni_exit_task);
if (!is_background_view) {
thread_host_.raster_thread->GetTaskRunner()->PostTask(jni_exit_task);
}
fml::WeakPtr weak_platform_view;
//创建PlatformViewAndroid
//创建on_create_platform_view
Shell::CreateCallback on_create_platform_view =
[is_background_view, &jni_facade, &weak_platform_view](Shell& shell) {
std::unique_ptr platform_view_android;
if (is_background_view) {
platform_view_android = std::make_unique(
shell, // delegate
shell.GetTaskRunners(), // task runners
jni_facade // JNI interop
);
} else {
platform_view_android = std::make_unique(
shell, // delegate
shell.GetTaskRunners(), // task runners
jni_facade, // JNI interop
shell.GetSettings()
.enable_software_rendering // use software rendering
);
}
weak_platform_view = platform_view_android->GetWeakPtr();
return platform_view_android;
};
Shell::CreateCallback on_create_rasterizer = [](Shell& shell) {
return std::make_unique(shell, shell.GetTaskRunners(),
shell.GetIsGpuDisabledSyncSwitch());
};
// 创建四个线程 并把当前线程设置platform thread
fml::MessageLoop::EnsureInitializedForCurrentThread();
fml::RefPtr gpu_runner;
fml::RefPtr ui_runner;
fml::RefPtr io_runner;
fml::RefPtr platform_runner =
fml::MessageLoop::GetCurrent().GetTaskRunner();
if (is_background_view) {
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 {
gpu_runner = thread_host_.raster_thread->GetTaskRunner();
ui_runner = thread_host_.ui_thread->GetTaskRunner();
io_runner = thread_host_.io_thread->GetTaskRunner();
}
flutter::TaskRunners task_runners(thread_label, // label
platform_runner, // platform
gpu_runner, // raster
ui_runner, // ui
io_runner // io
);
//shell创建
//不管是iOS,Android,linux,嵌入式平台,都有对应的 Shell::Create,差异最大的应该是web端,web端的整体架构方式就完全不同。
//Create的 时候传入platform view create
shell_ =
Shell::Create(task_runners, // task runners
GetDefaultWindowData(), // window data
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.GetRasterTaskRunner()->PostTask([]() {
// Android describes -8 as "most important display threads, for
// compositing the screen and retrieving input events". Conservatively
// set the raster thread to slightly lower priority than it.
if (::setpriority(PRIO_PROCESS, gettid(), -5) != 0) {
// Defensive fallback. Depending on the OEM, it may not be possible
// to set priority to -5.
if (::setpriority(PRIO_PROCESS, gettid(), -2) != 0) {
FML_LOG(ERROR) << "Failed to set GPU task runner priority";
}
}
});
task_runners.GetUITaskRunner()->PostTask([]() {
if (::setpriority(PRIO_PROCESS, gettid(), -1) != 0) {
FML_LOG(ERROR) << "Failed to set UI task runner priority";
}
});
}
}
Shell::Create中调用shell = CreateShellOnPlatformThread,然后回调on_create_platform_view
std::unique_ptr
- 创建shell
auto shell =
std::unique_ptr(new Shell(std::move(vm), task_runners, settings));
- 创建platform view
auto platform_view = on_create_platform_view(*shell.get());
if (!platform_view || !platform_view->GetWeakPtr()) {
return nullptr;
- 创建rasterizer
std::promise> rasterizer_promise;
auto rasterizer_future = rasterizer_promise.get_future();
std::promise> snapshot_delegate_promise;
auto snapshot_delegate_future = snapshot_delegate_promise.get_future();
fml::TaskRunner::RunNowOrPostTask(
task_runners.GetRasterTaskRunner(), [&rasterizer_promise, //
&snapshot_delegate_promise,
on_create_rasterizer, //
shell = shell.get() //
]() {
TRACE_EVENT0("flutter", "ShellSetupGPUSubsystem");
std::unique_ptr rasterizer(on_create_rasterizer(*shell));
snapshot_delegate_promise.set_value(rasterizer->GetSnapshotDelegate());
rasterizer_promise.set_value(std::move(rasterizer));
});
- 创建 IO manager
std::promise> io_manager_promise;
auto io_manager_future = io_manager_promise.get_future();
std::promise> weak_io_manager_promise;
auto weak_io_manager_future = weak_io_manager_promise.get_future();
std::promise> unref_queue_promise;
auto unref_queue_future = unref_queue_promise.get_future();
auto io_task_runner = shell->GetTaskRunners().GetIOTaskRunner();
- 创建 engine
std::promise> engine_promise;
auto engine_future = engine_promise.get_future();
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetUITaskRunner(),
fml::MakeCopyable([&engine_promise, //
shell = shell.get(), //
&dispatcher_maker, //
&window_data, //
isolate_snapshot = std::move(isolate_snapshot), //
vsync_waiter = std::move(vsync_waiter), //
&weak_io_manager_future, //
&snapshot_delegate_future, //
&unref_queue_future //
]() mutable {
TRACE_EVENT0("flutter", "ShellSetupUISubsystem");
const auto& task_runners = shell->GetTaskRunners();
// The animator is owned by the UI thread but it gets its vsync pulses
// from the platform.
auto animator = std::make_unique(*shell, task_runners,
std::move(vsync_waiter));
engine_promise.set_value(std::make_unique(
*shell, //
dispatcher_maker, //
*shell->GetDartVM(), //
std::move(isolate_snapshot), //
task_runners, //
window_data, //
shell->GetSettings(), //
std::move(animator), //
weak_io_manager_future.get(), //
unref_queue_future.get(), //
snapshot_delegate_future.get() //
));
}));