Flutter启动流程
Flutter Embedder层启动
一、FlutterApplication 阶段:初始化Flutter Engine(和FlutterEngine不同) so库
@Override@CallSuperpublic void onCreate() {super.onCreate();FlutterInjector.instance().flutterLoader().startInitialization(this);}
二、FlutterActivity#onCreate 阶段:初始化FlutterEngine(Java 类)和FlutterView
@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {switchLaunchThemeForNormalTheme();super.onCreate(savedInstanceState);// 创建代理类delegate = new FlutterActivityAndFragmentDelegate(this);// 初始化FlutterEnginedelegate.onAttach(this);delegate.onRestoreInstanceState(savedInstanceState);lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);configureWindowForTransparency();// 初始化FlutterViewsetContentView(createFlutterView());configureStatusBarForFullscreenFlutterExperience();}
2.1 初始化FlutterEngine(Java 类)
// FlutterActivityAndFragmentDelegatevoid onAttach(@NonNull Context context) {ensureAlive();if (flutterEngine == null) {// 初始化FlutterEnginesetupFlutterEngine();}if (host.shouldAttachEngineToActivity()) {flutterEngine.getActivityControlSurface().attachToActivity(this, host.getLifecycle());}@VisibleForTestingvoid setupFlutterEngine() {// 首先,若指明缓存则使用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;}// 其次,若Host(FlutterActivity或者FlutterFragment)提供则使用flutterEngine = host.provideFlutterEngine(host.getContext());if (flutterEngine != null) {isFlutterEngineFromHost = true;return;}// 最后新建一个实例flutterEngine =new FlutterEngine(host.getContext(),host.getFlutterShellArgs().toArray(),/*automaticallyRegisterPlugins=*/ false,/*willProvideRestorationData=*/ host.shouldRestoreAndSaveState());isFlutterEngineFromHost = false;}// FlutterEnginepublic FlutterEngine(@NonNull Context context,@Nullable FlutterLoader flutterLoader,@NonNull FlutterJNI flutterJNI,@NonNull PlatformViewsController platformViewsController,@Nullable String[] dartVmArgs,boolean automaticallyRegisterPlugins,boolean waitForRestorationData) {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;// 创建DartExecutor,负责Embedder 和 Framework 通信this.dartExecutor = new DartExecutor(flutterJNI, assetManager);// 设置FlutterJNI中处理Framework消息的 PlatformMessageHandlerthis.dartExecutor.onAttachedToJNI();DeferredComponentManager deferredComponentManager =FlutterInjector.instance().deferredComponentManager();// 提供给Framework的平台能力封装accessibilityChannel = new AccessibilityChannel(dartExecutor, flutterJNI);deferredComponentChannel = new DeferredComponentChannel(dartExecutor);keyEventChannel = new KeyEventChannel(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);systemChannel = new SystemChannel(dartExecutor);textInputChannel = new TextInputChannel(dartExecutor);if (deferredComponentManager != null) {deferredComponentManager.setDeferredComponentChannel(deferredComponentChannel);}this.localizationPlugin = new LocalizationPlugin(context, localizationChannel);if (flutterLoader == null) {flutterLoader = injector.flutterLoader();}if (!flutterJNI.isAttached()) {// 确保初始化完成// 此方法在FlutterApplication中会初始化一次flutterLoader.startInitialization(context.getApplicationContext());// 初始化一系列参数,比如:Framework 和 dart业务代码的加载// 初始化参数,通过flutterJNI.init --> FlutterJNI.nativeInitflutterLoader.ensureInitializationComplete(context, dartVmArgs);}flutterJNI.addEngineLifecycleListener(engineLifecycleListener);flutterJNI.setPlatformViewsController(platformViewsController);flutterJNI.setLocalizationPlugin(localizationPlugin);flutterJNI.setDeferredComponentManager(injector.deferredComponentManager());// It should typically be a fresh, unattached JNI. But on a spawned engine, the JNI instance// is already attached to a native shell. In that case, the Java FlutterEngine is created around// an existing shell.if (!flutterJNI.isAttached()) {attachToJni(); // 建立 Embedder和Engine连接,触发 flutterJNI.attachToNative();// --> performNativeAttach --> nativeAttach(flutterJNI);}// TODO(mattcarroll): FlutterRenderer is temporally coupled to attach(). Remove that coupling if// possible.this.renderer = new FlutterRenderer(flutterJNI);this.platformViewsController = platformViewsController;this.platformViewsController.onAttachedToJNI();this.pluginRegistry =new FlutterEngineConnectionRegistry(context.getApplicationContext(), this, flutterLoader);// Only automatically register plugins if both constructor parameter and// loaded AndroidManifest config turn this feature on.if (automaticallyRegisterPlugins && flutterLoader.automaticallyRegisterPlugins()) {GeneratedPluginRegister.registerGeneratedPlugins(this);}}
2.2 初始化FlutterView
@NonNullprivate View createFlutterView() {return delegate.onCreateView(/* inflater=*/ null,/* container=*/ null,/* savedInstanceState=*/ null,/*flutterViewId=*/ FLUTTER_VIEW_ID,/*shouldDelayFirstAndroidViewDraw=*/ getRenderMode() == RenderMode.surface);}// FlutterActivityAndFragmentDelegate@NonNullView 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);flutterView.setId(flutterViewId);SplashScreen splashScreen = host.provideSplashScreen();if (splashScreen != null) {Log.w(TAG,"A splash screen was provided to Flutter, but this is deprecated. See"+ " flutter.dev/go/android-splash-migration for migration steps.");FlutterSplashView flutterSplashView = new FlutterSplashView(host.getContext());flutterSplashView.setId(ViewUtils.generateViewId(FLUTTER_SPLASH_VIEW_FALLBACK_ID));flutterSplashView.displayFlutterViewWithSplash(flutterView, splashScreen);return flutterSplashView;}if (shouldDelayFirstAndroidViewDraw) {delayFirstAndroidViewDraw(flutterView);}return flutterView;}
三、FlutterActivity#onStart阶段:执行Dart入口代码
@Overrideprotected void onStart() {super.onStart();lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_START);if (stillAttachedForEvent("onStart")) {delegate.onStart();}}// FlutterActivityAndFragmentDelegatevoid onStart() {Log.v(TAG, "onStart()");ensureAlive();doInitialFlutterViewRun();flutterView.setVisibility(View.VISIBLE);}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();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());// 最终通过flutterJNI.runBundleAndSnapshotFromLibrary 启动flutter的framework层flutterEngine.getDartExecutor().executeDartEntrypoint(entrypoint, host.getDartEntrypointArgs());}
Flutter Engine层启动
在启动过程中,通过API回调或者JNI主动调用,Embedder已经多次调用了Engine的逻辑,其中有5处对于Engnie至关重要:
- JNI_OnLoad:在System.loadLibrary时触发,将完成Engine接口和Embedder接口的绑定注册。
- nativeInit:FlutterLoader主动调用,在相关资源准备完成后调用,主要负责向Engine传递必要的初始化参数
- nativeAttach:Embedder的FlutterEngine对象在完成必要的初始化后调用,将触发Engine中关键类的初始化逻辑()
- nativeSurfaceCreated:Java侧的Surface对象(SurfaceView)准备完成后调用,将触发Engine中有关绘制的逻辑的初始化。
- runBundleAndSnapshotFromLibrary:FlutterEngine和FlutterView均初始化完成后,在Host(比如:FlutterActivity)的onStart生命周期中主动调用,用于触发framework的相关初始化工作。
Flutter Framework层启动
Flutter 渲染管道
