Flutter-Android-加載

FlutterApplication 啟動(dòng)

FlutterApplication.onCreate

[FlutterApplication.java]

public void onCreate() {
    ...
    FlutterMain.startInitialization(this);
}

startInitialization

[FlutterMain.java]

    public static void startInitialization(Context applicationContext, FlutterMain.Settings settings) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            throw new IllegalStateException("startInitialization must be called on the main thread");
        } else if (sSettings == null) {
            sSettings = settings;
            long initStartTimestampMillis = SystemClock.uptimeMillis();
            initConfig(applicationContext);
            initAot(applicationContext);
            initResources(applicationContext);
            if (sResourceUpdater == null) {
                // 加載libflutter.so
                System.loadLibrary("flutter");
            } else {
                sResourceExtractor.waitForCompletion();
                File lib = new File(PathUtils.getDataDirectory(applicationContext), "libflutter.so");
                if (lib.exists()) {
                    System.load(lib.getAbsolutePath());
                } else {
                    System.loadLibrary("flutter");
                }
            }

            long initTimeMillis = SystemClock.uptimeMillis() - initStartTimestampMillis;
            nativeRecordStartTimestamp(initTimeMillis);
        }
    }

這個(gè)方法主要做的事情:

  • 初始化配置仅叫,獲取是否預(yù)編譯模式屁擅,初始化并提取資源文件芭概;
  • 加載libflutter.so庫;
  • 記錄啟動(dòng)時(shí)間戳昏苏;

initConfig

[FlutterMain.java]

    private static void initConfig(Context applicationContext) {
        try {
            // metaData 信息
            Bundle metadata = applicationContext.getPackageManager().getApplicationInfo(applicationContext.getPackageName(), 128).metaData;
            if (metadata != null) {
                sAotSharedLibraryPath = metadata.getString(PUBLIC_AOT_AOT_SHARED_LIBRARY_PATH, "app.so");
                sAotVmSnapshotData = metadata.getString(PUBLIC_AOT_VM_SNAPSHOT_DATA_KEY, "vm_snapshot_data");
                sAotVmSnapshotInstr = metadata.getString(PUBLIC_AOT_VM_SNAPSHOT_INSTR_KEY, "vm_snapshot_instr");
                sAotIsolateSnapshotData = metadata.getString(PUBLIC_AOT_ISOLATE_SNAPSHOT_DATA_KEY, "isolate_snapshot_data");
                sAotIsolateSnapshotInstr = metadata.getString(PUBLIC_AOT_ISOLATE_SNAPSHOT_INSTR_KEY, "isolate_snapshot_instr");
                sFlx = metadata.getString(PUBLIC_FLX_KEY, "app.flx");
                sFlutterAssetsDir = metadata.getString(PUBLIC_FLUTTER_ASSETS_DIR_KEY, "flutter_assets");
            }

        } catch (NameNotFoundException var2) {
            throw new RuntimeException(var2);
        }
    }

初始化FlutterMain的相關(guān)配置信息,當(dāng)metadata數(shù)據(jù)沒有配置初值則采用默認(rèn)值

initAot

[FlutterMain.java]

    private static void initAot(Context applicationContext) {
        Set<String> assets = listAssets(applicationContext, "");
        sIsPrecompiledAsBlobs = assets.containsAll(Arrays.asList(sAotVmSnapshotData, sAotVmSnapshotInstr, sAotIsolateSnapshotData, sAotIsolateSnapshotInstr));
        sIsPrecompiledAsSharedLibrary = assets.contains(sAotSharedLibraryPath);
        // 當(dāng)assets中存在共享庫app.so和Dart虛擬機(jī)快照例获,則是預(yù)編譯應(yīng)用拋出異常
        if (sIsPrecompiledAsBlobs && sIsPrecompiledAsSharedLibrary) {
            throw new RuntimeException("Found precompiled app as shared library and as Dart VM snapshots.");
        }
    }

initResources

    private static void initResources(Context applicationContext) {
        Context context = applicationContext;
        (new ResourceCleaner(applicationContext)).start();
        Bundle metaData = null;

        try {
            metaData = context.getPackageManager().getApplicationInfo(context.getPackageName(), 128).metaData;
        } catch (NameNotFoundException var4) {
            ...
        }
        // 資源更新
        if (metaData != null && metaData.getBoolean("DynamicPatching")) {
            sResourceUpdater = new ResourceUpdater(applicationContext);
            if (sResourceUpdater.getDownloadMode() == DownloadMode.ON_RESTART || sResourceUpdater.getDownloadMode() == DownloadMode.ON_RESUME) {
                sResourceUpdater.startUpdateDownloadOnce();
                // 異步操作
                if (sResourceUpdater.getInstallMode() == InstallMode.IMMEDIATE) {
                    sResourceUpdater.waitForDownloadCompletion();
                }
            }
        }
        // 資源提取
        sResourceExtractor = new ResourceExtractor(applicationContext);
        sResourceExtractor.addResource(fromFlutterAssets(sFlx)).addResource(fromFlutterAssets(sAotVmSnapshotData)).addResource(fromFlutterAssets(sAotVmSnapshotInstr)).addResource(fromFlutterAssets(sAotIsolateSnapshotData)).addResource(fromFlutterAssets(sAotIsolateSnapshotInstr)).addResource(fromFlutterAssets("kernel_blob.bin"));
        if (sIsPrecompiledAsSharedLibrary) {
            sResourceExtractor.addResource(sAotSharedLibraryPath);
        } else {
            sResourceExtractor.addResource(sAotVmSnapshotData).addResource(sAotVmSnapshotInstr).addResource(sAotIsolateSnapshotData).addResource(sAotIsolateSnapshotInstr);
        }

        if (sResourceUpdater != null) {
            sResourceExtractor.addResource("libflutter.so");
        }

        sResourceExtractor.start();
    }

資源初始化主要包括對(duì)資源文件的清理油宜、更新以及提前操作,這個(gè)過程都是在異步線程執(zhí)行完成者甲。

System.loadLibrary

不論是System.loadLibrary()春感,還是System.load()最終都會(huì)調(diào)用到該加載庫中的JNI_OnLoad()方法砌创,

[flutter/shell/platform/android/library_loader.cc]

JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
  // 初始化Java虛擬機(jī)
  fml::jni::InitJavaVM(vm);
  // 將當(dāng)前線程和JavaVM建立關(guān)聯(lián)
  JNIEnv* env = fml::jni::AttachCurrentThread();
  bool result = false;

  // 注冊FlutterMain
  result = shell::FlutterMain::Register(env);

  // 注冊PlatformView
  result = shell::PlatformViewAndroid::Register(env);

  // 注冊VSyncWaiter
  result = shell::VsyncWaiterAndroid::Register(env);
  return JNI_VERSION_1_4;
}

InitJavaVM

jni_util.cc

void InitJavaVM(JavaVM* vm) {
  g_jvm = vm;
}

JNIEnv* AttachCurrentThread() {
  JNIEnv* env = nullptr;
  jint ret = g_jvm->AttachCurrentThread(&env, nullptr);
  FML_DCHECK(JNI_OK == ret);
  return env;
}

將當(dāng)前進(jìn)程的JavaVM實(shí)例保存在靜態(tài)變量虏缸,再將當(dāng)前線程和JavaVM建立關(guān)聯(lián),獲取JNIEnv實(shí)例嫩实,每個(gè)線程對(duì)應(yīng)一個(gè)JNIEnv實(shí)例刽辙。

FlutterMain::Register

flutter_main.cc

bool FlutterMain::Register(JNIEnv* env) {
  static const JNINativeMethod methods[] = {
      {
          .name = "nativeInit",
          .signature = "(Landroid/content/Context;[Ljava/lang/String;Ljava/"
                       "lang/String;Ljava/lang/String;Ljava/lang/String;)V",
          .fnPtr = reinterpret_cast<void*>(&Init),
      },
      {
          .name = "nativeRecordStartTimestamp",
          .signature = "(J)V",
          .fnPtr = reinterpret_cast<void*>(&RecordStartTimestamp),
      },
  };

  jclass clazz = env->FindClass("io/flutter/embedding/engine/FlutterJNI");
  ...
  return env->RegisterNatives(clazz, methods, fml::size(methods)) == 0;
}

注冊了FlutterMain的nativeInit和nativeRecordStartTimestamp的兩方法

PlatformViewAndroid::Register

platform_view_android_jni.cc

bool PlatformViewAndroid::Register(JNIEnv* env) {
  if (env == nullptr) {
    return false;
  }
  // FlutterCallbackInformation(String,String)
  g_flutter_callback_info_class = new fml::jni::ScopedJavaGlobalRef<jclass>(
      env, env->FindClass("io/flutter/view/FlutterCallbackInformation"));
  ...
  g_flutter_callback_info_constructor = env->GetMethodID(
      g_flutter_callback_info_class->obj(), "<init>",
      "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
  ...
  // FlutterJNI
  g_flutter_jni_class = new fml::jni::ScopedJavaGlobalRef<jclass>(
      env, env->FindClass("io/flutter/embedding/engine/FlutterJNI"));
  ...
  // SurfaceTexture.attachToGLContext(int)
  g_surface_texture_class = new fml::jni::ScopedJavaGlobalRef<jclass>(
      env, env->FindClass("android/graphics/SurfaceTexture"));
  ...
  g_attach_to_gl_context_method = env->GetMethodID(
      g_surface_texture_class->obj(), "attachToGLContext", "(I)V");
  ...
  // SurfaceTexture.updateTexImage()
  g_update_tex_image_method =
      env->GetMethodID(g_surface_texture_class->obj(), "updateTexImage", "()V");
  ...
  // SurfaceTexture.getTransformMatrix(float[])
  g_get_transform_matrix_method = env->GetMethodID(
      g_surface_texture_class->obj(), "getTransformMatrix", "([F)V");
  ...
  // SurfaceTexture.detachFromGLContext()
  g_detach_from_gl_context_method = env->GetMethodID(
      g_surface_texture_class->obj(), "detachFromGLContext", "()V");
  ...
  return RegisterApi(env);
}
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<void*>(&AttachJNI),
      },
      ...
      {
          .name = "nativeLookupCallbackInformation",
          .signature = "(J)Lio/flutter/view/FlutterCallbackInformation;",
          .fnPtr = reinterpret_cast<void*>(&LookupCallbackInformation),
      },
  };

  if (env->RegisterNatives(g_flutter_jni_class->obj(), flutter_jni_methods,
                           fml::size(flutter_jni_methods)) != 0) {
    return false;
  }

  g_handle_platform_message_method =
      env->GetMethodID(g_flutter_jni_class->obj(), "handlePlatformMessage",
                       "(Ljava/lang/String;[BI)V");
  ...
  if (g_on_engine_restart_method == nullptr) {
    FML_LOG(ERROR) << "Could not locate onEngineRestart method";
    return false;
  }

  return true;
}

該方法的主要工作:通過RegisterNatives()注冊一些類的Native方法,用于Java調(diào)用C++的過程甲献;通過GetMethodID()等方法記錄了一些Java方法的jmethodID宰缤,用于C++調(diào)用Java的過程。

VsyncWaiterAndroid::Register

vsync_waiter_android.cc

bool VsyncWaiterAndroid::Register(JNIEnv* env) {
  static const JNINativeMethod methods[] = {{
      .name = "nativeOnVsync",
      .signature = "(JJJ)V",
      .fnPtr = reinterpret_cast<void*>(&OnNativeVsync),
  }};

  jclass clazz = env->FindClass("io/flutter/embedding/engine/FlutterJNI");
  g_vsync_waiter_class = new fml::jni::ScopedJavaGlobalRef<jclass>(env, clazz);
  g_async_wait_for_vsync_method_ = env->GetStaticMethodID(
      g_vsync_waiter_class->obj(), "asyncWaitForVsync", "(J)V");
  return env->RegisterNatives(clazz, methods, fml::size(methods)) == 0;
}

該注冊過程主要工作:

  • 將Java層的VsyncWaiter類的nativeOnVsync()方法,映射到C++層的OnNativeVsync()方法修肠,用于該方法的Java調(diào)用C++的過程鳖擒;
  • 將Java層的VsyncWaiter類的asyncWaitForVsync()方法岳颇,保存到C++層的g_async_wait_for_vsync_method_變量,用于該方法C++調(diào)用Java的過程呻疹。

FlutterActivity 啟動(dòng)流程

FlutterActivity.onCreate

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.eventDelegate.onCreate(savedInstanceState);
}

調(diào)用代理的onCreate方法

FlutterActivityDelegate.onCreate

public void onCreate(Bundle savedInstanceState) {
    // 設(shè)置Widow相關(guān)屬性
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Window window = activity.getWindow();
        window.addFlags(LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(0x40000000);
        window.getDecorView().setSystemUiVisibility(PlatformPlugin.DEFAULT_SYSTEM_UI);
    }
    // 從Intent中提取參數(shù)
    String[] args = getArgsFromIntent(this.activity.getIntent());
    // 初始數(shù)據(jù)
    FlutterMain.ensureInitializationComplete(this.activity.getApplicationContext(), args);
    // 此處viewFactory便是FlutterActivity,該方法目前返回值為null
    this.flutterView = this.viewFactory.createFlutterView(this.activity);
    if (this.flutterView == null) {// 默認(rèn)會(huì)走到這里
        // 這里默認(rèn)為空
        FlutterNativeView nativeView = this.viewFactory.createFlutterNativeView();
        // 初始 FlutterView 下面有講到
        this.flutterView = new FlutterView(this.activity, (AttributeSet)null, nativeView);
        // 將flutterView設(shè)置到Activity中
        this.flutterView.setLayoutParams(matchParent);
        this.activity.setContentView(this.flutterView);
        this.launchView = this.createLaunchView();
        // 過度的View
        if (this.launchView != null) {
            this.addLaunchView();
        }
    }

    if (!this.loadIntent(this.activity.getIntent())) {
        String appBundlePath = FlutterMain.findAppBundlePath(this.activity.getApplicationContext());
        if (appBundlePath != null) {
            this.runBundle(appBundlePath);
        }

    }
}

FlutterMain.ensureInitializationComplete

public static void ensureInitializationComplete(Context applicationContext, String[] args) {
    if (Looper.myLooper() != Looper.getMainLooper()) {
        throw new IllegalStateException("ensureInitializationComplete must be called on the main thread");
    } else if (sSettings == null) { // 保證sSettings完成初始化賦值筹陵;
        throw new IllegalStateException("ensureInitializationComplete must be called after startInitialization");
    } else if (!sInitialized) {
        try {
            // 保證sResourceExtractor完成資源文件的提取工作
            sResourceExtractor.waitForCompletion();
            // 拼接參數(shù)
            List<String> shellArgs = new ArrayList();
            shellArgs.add("--icu-symbol-prefix=_binary_icudtl_dat");
            ApplicationInfo applicationInfo = applicationContext.getPackageManager().getApplicationInfo(applicationContext.getPackageName(), 128);
            shellArgs.add("--icu-native-lib-path=" + applicationInfo.nativeLibraryDir + File.separator + "libflutter.so");
            if (args != null) {
                Collections.addAll(shellArgs, args);
            }

            if (sIsPrecompiledAsSharedLibrary) {
                shellArgs.add("--aot-shared-library-path=" + new File(PathUtils.getDataDirectory(applicationContext), sAotSharedLibraryPath));
            } else {
                if (sIsPrecompiledAsBlobs) {
                    shellArgs.add("--aot-snapshot-path=" + PathUtils.getDataDirectory(applicationContext));
                } else {
                    shellArgs.add("--cache-dir-path=" + PathUtils.getCacheDirectory(applicationContext));
                    shellArgs.add("--aot-snapshot-path=" + PathUtils.getDataDirectory(applicationContext) + "/" + sFlutterAssetsDir);
                }

                shellArgs.add("--vm-snapshot-data=" + sAotVmSnapshotData);
                shellArgs.add("--vm-snapshot-instr=" + sAotVmSnapshotInstr);
                shellArgs.add("--isolate-snapshot-data=" + sAotIsolateSnapshotData);
                shellArgs.add("--isolate-snapshot-instr=" + sAotIsolateSnapshotInstr);
            }

            if (sSettings.getLogTag() != null) {
                shellArgs.add("--log-tag=" + sSettings.getLogTag());
            }

            String appBundlePath = findAppBundlePath(applicationContext);
            String appStoragePath = PathUtils.getFilesDir(applicationContext);
            String engineCachesPath = PathUtils.getCacheDirectory(applicationContext);
            // 初始化native相關(guān)信息
            nativeInit(applicationContext, (String[])shellArgs.toArray(new String[0]), appBundlePath, appStoragePath, engineCachesPath);
            sInitialized = true;
        } catch (Exception var7) {
            Log.e("FlutterMain", "Flutter initialization failed.", var7);
            throw new RuntimeException(var7);
        }
    }
}

這個(gè)方法主要的工作:

  • 保證該操作運(yùn)行在主線程刽锤;
  • 保證sSettings完成初始化賦值;
  • 保證sResourceExtractor完成資源文件的提取工作朦佩;
  • 拼接所有相關(guān)的shellArgs并思,包括intent中的參數(shù);
  • 執(zhí)行nativeInit來初始化native相關(guān)信息语稠;

FlutterMain::Init

在上面的(FlutterMain::Register)分析中 nativeInit所對(duì)應(yīng)的方法FlutterMain::Init()

void FlutterMain::Init(JNIEnv* env,
                       jclass clazz,
                       jobject context,
                       jobjectArray jargs,
                       jstring bundlePath,
                       jstring appStoragePath,
                       jstring engineCachesPath) {
  std::vector<std::string> args;
  args.push_back("flutter");
  for (auto& arg : fml::jni::StringArrayToVector(env, jargs)) {
    args.push_back(std::move(arg));
  }
  auto command_line = fml::CommandLineFromIterators(args.begin(), args.end());
  // 根據(jù)args生成Settings結(jié)構(gòu)體宋彼,記錄所有相關(guān)參數(shù)
  auto settings = SettingsFromCommandLine(command_line);

  settings.assets_path = fml::jni::JavaStringToString(env, bundlePath);

  flutter::DartCallbackCache::SetCachePath(
      fml::jni::JavaStringToString(env, appStoragePath));

  fml::paths::InitializeAndroidCachesPath(
      fml::jni::JavaStringToString(env, engineCachesPath));
  // 從磁盤中加載緩存
  flutter::DartCallbackCache::LoadCacheFromDisk();

  if (!flutter::DartVM::IsRunningPrecompiledCode()) {
    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;
    }
  }
  // 初始化observer的增加和刪除方法
  settings.task_observer_add = [](intptr_t key, fml::closure callback) {
    fml::MessageLoop::GetCurrent().AddTaskObserver(key, std::move(callback));
  };

  settings.task_observer_remove = [](intptr_t key) {
    fml::MessageLoop::GetCurrent().RemoveTaskObserver(key);
  };
  // 
  g_flutter_main.reset(new FlutterMain(std::move(settings)));
}

該方法主要功能args以及各種資源文件路徑細(xì)信息都保存在Settings結(jié)構(gòu)體,記錄在FlutterMain中颅筋,最后記錄在g_flutter_main靜態(tài)變量宙暇。

FlutterView 初始化

public FlutterView(Context context, AttributeSet attrs, FlutterNativeView nativeView) {
        super(context, attrs);
        ...
        Activity activity = getActivity(this.getContext());
        if (activity == null) {
            throw new IllegalArgumentException("Bad context");
        } else {
            if (nativeView == null) {
                // 初始化FlutterNativeView
                this.mNativeView = new FlutterNativeView(activity.getApplicationContext());
            } else {
                this.mNativeView = nativeView;
            }

            this.dartExecutor = this.mNativeView.getDartExecutor();
            this.flutterRenderer = new FlutterRenderer(this.mNativeView.getFlutterJNI());
            this.mIsSoftwareRenderingEnabled = FlutterJNI.nativeGetIsSoftwareRenderingEnabled();
            ...
            // 關(guān)聯(lián)activity
            this.mNativeView.attachViewAndActivity(this, activity);
            this.mSurfaceCallback = new Callback() {
                public void surfaceCreated(SurfaceHolder holder) {
                    FlutterView.this.assertAttached();
                    FlutterView.this.mNativeView.getFlutterJNI().onSurfaceCreated(holder.getSurface());
                }

                public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                    FlutterView.this.assertAttached();
                    FlutterView.this.mNativeView.getFlutterJNI().onSurfaceChanged(width, height);
                }

                public void surfaceDestroyed(SurfaceHolder holder) {
                    FlutterView.this.assertAttached();
                    FlutterView.this.mNativeView.getFlutterJNI().onSurfaceDestroyed();
                }
            };
            this.getHolder().addCallback(this.mSurfaceCallback);
            ...
            // 創(chuàng)建所有的平臺(tái)通道channels
            this.navigationChannel = new NavigationChannel(this.dartExecutor);
            ...
            
            // 創(chuàng)建并設(shè)置插件
            PlatformPlugin platformPlugin = new PlatformPlugin(activity, this.platformChannel);
            this.addActivityLifecycleListener(platformPlugin);
            this.mImm = (InputMethodManager)this.getContext().getSystemService("input_method");
            ...

            // 發(fā)送初始化平臺(tái)臺(tái)的消息發(fā)送給Dart
            this.sendLocalesToDart(this.getResources().getConfiguration());
            this.sendUserPlatformSettingsToDart();
        }
    }

這個(gè)方法主要做的事情

  • 初始化變量
  • 初始化 FlutterNativeView
  • 創(chuàng)建所有的平臺(tái)通道channels
  • 創(chuàng)建并設(shè)置插件

FlutterNativeView 初始化

public FlutterNativeView(@NonNull Context context, boolean isBackgroundView) {
    this.mContext = context;
    this.mPluginRegistry = new FlutterPluginRegistry(this, context);
    this.mFlutterJNI = new FlutterJNI();
    this.mFlutterJNI.setRenderSurface(new FlutterNativeView.RenderSurfaceImpl());
    this.dartExecutor = new DartExecutor(this.mFlutterJNI);
    this.mFlutterJNI.addEngineLifecycleListener(new FlutterNativeView.EngineLifecycleListenerImpl());
    this.attach(this, isBackgroundView);
    this.assertAttached();
}

這個(gè)方法主要做的是,對(duì)一些變量的初始操作,包括 FlutterPluginRegistry FlutterJNI RenderSurfaceImpl DartExecutor议泵。并執(zhí)行Attached方法

FlutterNativeView.attach

private void attach(FlutterNativeView view, boolean isBackgroundView) {
    this.mFlutterJNI.attachToNative(isBackgroundView);
    this.dartExecutor.onAttachedToJNI();
}
@UiThread
public void attachToNative(boolean isBackgroundView) {
    this.ensureNotAttachedToNative();
    this.nativePlatformViewId = this.nativeAttach(this, isBackgroundView);
}

AttachJNI

platform_view_android_jni.cc

static jlong AttachJNI(JNIEnv* env,
                       jclass clazz,
                       jobject flutterJNI,
                       jboolean is_background_view) {
  fml::jni::JavaObjectWeakGlobalRef java_object(env, flutterJNI);
  // 在引擎層初始化AndroidShellHolder對(duì)象
  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;
  }
}

Flutter引擎啟動(dòng)

AndroidShellHolder 初始化

AndroidShellHolder::AndroidShellHolder(
    flutter::Settings settings,
    fml::jni::JavaObjectWeakGlobalRef java_object,
    bool is_background_view)
    : settings_(std::move(settings)), java_object_(java_object) {
  static size_t shell_count = 1;
  auto thread_label = std::to_string(shell_count++);
  //創(chuàng)建線程私有的key
  FML_CHECK(pthread_key_create(&thread_destruct_key_, ThreadDestructCallback) ==
            0);

  //創(chuàng)建目標(biāo)線程
  if (is_background_view) {
    ...
  } else {
    thread_host_ = {thread_label, ThreadHost::Type::UI | ThreadHost::Type::GPU |
                                      ThreadHost::Type::IO};
  }

  // Detach from JNI when the UI and GPU threads exit.
  // 當(dāng)UI和GPU線程退出時(shí)從JNI分離占贫。
  auto jni_exit_task([key = thread_destruct_key_]() {
    FML_CHECK(pthread_setspecific(key, reinterpret_cast<void*>(1)) == 0);
  });
  thread_host_.ui_thread->GetTaskRunner()->PostTask(jni_exit_task);
  if (!is_background_view) {
    thread_host_.gpu_thread->GetTaskRunner()->PostTask(jni_exit_task);
  }

  fml::WeakPtr<PlatformViewAndroid> weak_platform_view;
  Shell::CreateCallback<PlatformView> on_create_platform_view =
      [is_background_view, java_object, &weak_platform_view](Shell& shell) {
        std::unique_ptr<PlatformViewAndroid> platform_view_android;
        if (is_background_view) {
            ...
        } 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;
      };

  Shell::CreateCallback<Rasterizer> on_create_rasterizer = [](Shell& shell) {
    return std::make_unique<Rasterizer>(shell, shell.GetTaskRunners());
  };

  // The current thread will be used as the platform thread. Ensure that the
  // message loop is initialized.
  // 當(dāng)前主線程初始化MesageLoop
  fml::MessageLoop::EnsureInitializedForCurrentThread();
  // gpu,ui先口,io 三個(gè)線程
  fml::RefPtr<fml::TaskRunner> gpu_runner;
  fml::RefPtr<fml::TaskRunner> ui_runner;
  fml::RefPtr<fml::TaskRunner> io_runner;
  fml::RefPtr<fml::TaskRunner> platform_runner =
      fml::MessageLoop::GetCurrent().GetTaskRunner();
  if (is_background_view) {
    ...
  } else {
    gpu_runner = thread_host_.gpu_thread->GetTaskRunner();
    ui_runner = thread_host_.ui_thread->GetTaskRunner();
    io_runner = thread_host_.io_thread->GetTaskRunner();
  }
  // 創(chuàng)建task_runners對(duì)象
  flutter::TaskRunners task_runners(thread_label,     // label
                                    platform_runner,  // platform
                                    gpu_runner,       // gpu
                                    ui_runner,        // ui
                                    io_runner         // io
  );
  // 創(chuàng)建Shell對(duì)象
  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;
  is_valid_ = shell_ != nullptr;
  if (is_valid_) { // 可用
    // 提升ui線程和gpu線程的優(yōu)先級(jí)
    task_runners.GetGPUTaskRunner()->PostTask([]() {
      // Android describes -8 as "most important display threads, for
      // compositing the screen and retrieving input events". Conservatively
      // set the GPU 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";
      }
    });
  }
}

該方法的主要功能:

  • 創(chuàng)建ui型奥,gpu,io這3個(gè)線程碉京,并分別初始化MessageLoop
  • on_create_platform_view on_create_rasterizer
  • 創(chuàng)建Shell對(duì)象厢汹,TaskRunners對(duì)象

ThreadHost

看一下線程創(chuàng)建的過程
thread_host.cc

ThreadHost::ThreadHost(std::string name_prefix, uint64_t mask) {
  if (mask & ThreadHost::Type::Platform) {
    platform_thread = std::make_unique<fml::Thread>(name_prefix + ".platform");
  }

  if (mask & ThreadHost::Type::UI) {
    ui_thread = std::make_unique<fml::Thread>(name_prefix + ".ui");
  }

  if (mask & ThreadHost::Type::GPU) {
    gpu_thread = std::make_unique<fml::Thread>(name_prefix + ".gpu");
  }

  if (mask & ThreadHost::Type::IO) {
    io_thread = std::make_unique<fml::Thread>(name_prefix + ".io");
  }
}

根據(jù)傳遞的參數(shù),可知首次創(chuàng)建AndroidShellHolder實(shí)例的過程谐宙,會(huì)創(chuàng)建1.ui, 1.gpu, 1.io這3個(gè)線程烫葬。每個(gè)線程Thread初始化過程,都會(huì)創(chuàng)建相應(yīng)的MessageLoop凡蜻、TaskRunner對(duì)象搭综,然后進(jìn)入pollOnce輪詢等待狀態(tài)

Shell::Create

std::unique_ptr<Shell> Shell::Create(
    TaskRunners task_runners,
    Settings settings,
    Shell::CreateCallback<PlatformView> on_create_platform_view,
    Shell::CreateCallback<Rasterizer> on_create_rasterizer) {
  // 初始化對(duì)應(yīng)平臺(tái)信息。比如設(shè)置日志輸入划栓,記錄啟動(dòng)時(shí)間兑巾,Skia初始化等
  PerformInitializationTasks(settings);
  PersistentCache::SetCacheSkSL(settings.cache_sksl);

  // 創(chuàng)建虛擬機(jī)
  auto vm = DartVMRef::Create(settings);
  FML_CHECK(vm) << "Must be able to initialize the VM.";
  auto vm_data = vm->GetVMData();

  return Shell::Create(std::move(task_runners),             //
                       std::move(settings),                 //
                       vm_data->GetIsolateSnapshot(),       // isolate snapshot
                       std::move(on_create_platform_view),  //
                       std::move(on_create_rasterizer),     //
                       std::move(vm)                        //
  );
}

該方法的主要功能:更加傳遞的參數(shù),設(shè)置一些屬性等

DartVMRef::Create

dart_vm_lifecycle.cc

DartVMRef DartVMRef::Create(Settings settings,
                            fml::RefPtr<DartSnapshot> vm_snapshot,
                            fml::RefPtr<DartSnapshot> isolate_snapshot) {
  std::scoped_lock lifecycle_lock(gVMMutex);


  // If there is already a running VM in the process, grab a strong reference to
  // it.
  // 當(dāng)該進(jìn)程存在一個(gè)正在運(yùn)行虛擬機(jī)忠荞,則獲取其強(qiáng)引用蒋歌,復(fù)用該虛擬機(jī)
  if (auto vm = gVM.lock()) {
    FML_DLOG(WARNING) << "Attempted to create a VM in a process where one was "
                         "already running. Ignoring arguments for current VM "
                         "create call and reusing the old VM.";
    // There was already a running VM in the process,
    return DartVMRef{std::move(vm)};
  }

  std::scoped_lock dependents_lock(gVMDependentsMutex);
  // reset()
  gVMData.reset();
  gVMServiceProtocol.reset();
  gVMIsolateNameServer.reset();
  gVM.reset();

  // If there is no VM in the process. Initialize one, hold the weak reference
  // and pass a strong reference to the caller.
  auto isolate_name_server = std::make_shared<IsolateNameServer>();
  //創(chuàng)建虛擬機(jī)
  auto vm = DartVM::Create(std::move(settings),          //
                           std::move(vm_snapshot),       //
                           std::move(isolate_snapshot),  //
                           isolate_name_server           //
  );


  gVMData = vm->GetVMData();
  gVMServiceProtocol = vm->GetServiceProtocol();
  gVMIsolateNameServer = isolate_name_server;
  gVM = vm;

  if (settings.leak_vm) {
    gVMLeak = new std::shared_ptr<DartVM>(vm);
  }

  return DartVMRef{std::move(vm)};
}

Shell::Create

std::unique_ptr<Shell> Shell::Create(
    TaskRunners task_runners,
    Settings settings,
    fml::RefPtr<const DartSnapshot> isolate_snapshot,
    Shell::CreateCallback<PlatformView> on_create_platform_view,
    Shell::CreateCallback<Rasterizer> on_create_rasterizer,
    DartVMRef vm) {
  ...
  fml::AutoResetWaitableEvent latch;
  std::unique_ptr<Shell> shell;
  fml::TaskRunner::RunNowOrPostTask(
      task_runners.GetPlatformTaskRunner(),
      fml::MakeCopyable([&latch,                                          //
                         vm = std::move(vm),                              //
                         &shell,                                          //
                         task_runners = std::move(task_runners),          //
                         settings,                                        //
                         isolate_snapshot = std::move(isolate_snapshot),  //
                         on_create_platform_view,                         //
                         on_create_rasterizer                             //
  ]() mutable {
        // 創(chuàng)建shell的地方
        shell = CreateShellOnPlatformThread(std::move(vm),
                                            std::move(task_runners),      //
                                            settings,                     //
                                            std::move(isolate_snapshot),  //
                                            on_create_platform_view,      //
                                            on_create_rasterizer          //
        );
        latch.Signal();
      }));
  latch.Wait();
  return shell;
}

Shell::CreateShellOnPlatformThread

std::unique_ptr<Shell> Shell::CreateShellOnPlatformThread(
    DartVMRef vm,
    TaskRunners task_runners,
    Settings settings,
    fml::RefPtr<const DartSnapshot> isolate_snapshot,
    Shell::CreateCallback<PlatformView> on_create_platform_view,
    Shell::CreateCallback<Rasterizer> on_create_rasterizer) {

  // new Shell
  auto shell =
      std::unique_ptr<Shell>(new Shell(std::move(vm), task_runners, settings));

  // Create the rasterizer on the GPU thread.
  // GPU 線程創(chuàng)建 rasterizer
  std::promise<std::unique_ptr<Rasterizer>> rasterizer_promise;
  auto rasterizer_future = rasterizer_promise.get_future();
  std::promise<fml::WeakPtr<SnapshotDelegate>> snapshot_delegate_promise;
  auto snapshot_delegate_future = snapshot_delegate_promise.get_future();
  fml::TaskRunner::RunNowOrPostTask(
      task_runners.GetGPUTaskRunner(), [&rasterizer_promise,  //
                                        &snapshot_delegate_promise,
                                        on_create_rasterizer,  //
                                        shell = shell.get()    //
  ]() {
        TRACE_EVENT0("flutter", "ShellSetupGPUSubsystem");
        std::unique_ptr<Rasterizer> rasterizer(on_create_rasterizer(*shell));
        snapshot_delegate_promise.set_value(rasterizer->GetSnapshotDelegate());
        rasterizer_promise.set_value(std::move(rasterizer));
      });

  // Create the platform view on the platform thread (this thread).
  // 在主線程創(chuàng)建 platform view
  auto platform_view = on_create_platform_view(*shell.get());

  // Ask the platform view for the vsync waiter. This will be used by the engine
  // to create the animator.
  // 創(chuàng)建 vsync_waiter
  auto vsync_waiter = platform_view->CreateVSyncWaiter();

  // Create the IO manager on the IO thread. The IO manager must be initialized
  // first because it has state that the other subsystems depend on. It must
  // first be booted and the necessary references obtained to initialize the
  // other subsystems.
  std::promise<std::unique_ptr<ShellIOManager>> io_manager_promise;
  auto io_manager_future = io_manager_promise.get_future();
  std::promise<fml::WeakPtr<ShellIOManager>> weak_io_manager_promise;
  auto weak_io_manager_future = weak_io_manager_promise.get_future();
  std::promise<fml::RefPtr<SkiaUnrefQueue>> unref_queue_promise;
  auto unref_queue_future = unref_queue_promise.get_future();
  auto io_task_runner = shell->GetTaskRunners().GetIOTaskRunner();

  fml::TaskRunner::RunNowOrPostTask(
      io_task_runner,
      [&io_manager_promise,                          //
       &weak_io_manager_promise,                     //
       &unref_queue_promise,                         //
       platform_view = platform_view->GetWeakPtr(),  //
       io_task_runner                                //
  ]() {
        // 在io線程中創(chuàng)建ShellIOManager對(duì)象
        auto io_manager = std::make_unique<ShellIOManager>(
            platform_view.getUnsafe()->CreateResourceContext(), io_task_runner);
        weak_io_manager_promise.set_value(io_manager->GetWeakPtr());
        unref_queue_promise.set_value(io_manager->GetSkiaUnrefQueue());
        io_manager_promise.set_value(std::move(io_manager));
      });

  // Send dispatcher_maker to the engine constructor because shell won't have
  // platform_view set until Shell::Setup is called later.
  auto dispatcher_maker = platform_view->GetDispatcherMaker();

  // Create the engine on the UI thread.
  std::promise<std::unique_ptr<Engine>> engine_promise;
  auto engine_future = engine_promise.get_future();
  fml::TaskRunner::RunNowOrPostTask(
      shell->GetTaskRunners().GetUITaskRunner(),
      fml::MakeCopyable([&engine_promise,                                 //
                         shell = shell.get(),                             //
                         &dispatcher_maker,                               //
                         isolate_snapshot = std::move(isolate_snapshot),  //
                         vsync_waiter = std::move(vsync_waiter),          //
                         &weak_io_manager_future,                         //
                         &snapshot_delegate_future,                       //
                         &unref_queue_future                              //
  ]() mutable {
        
        const auto& task_runners = shell->GetTaskRunners();

        // The animator is owned by the UI thread but it gets its vsync pulses
        // from the platform.
        // 創(chuàng)建Animator對(duì)象 
        auto animator = std::make_unique<Animator>(*shell, task_runners,
                                                   std::move(vsync_waiter));
        // 在ui線程中創(chuàng)建Engine對(duì)象
        engine_promise.set_value(std::make_unique<Engine>(
            *shell,                         //
            dispatcher_maker,               //
            *shell->GetDartVM(),            //
            std::move(isolate_snapshot),    //
            task_runners,                   //
            shell->GetSettings(),           //
            std::move(animator),            //
            weak_io_manager_future.get(),   //
            unref_queue_future.get(),       //
            snapshot_delegate_future.get()  //
            ));
      }));

  if (!shell->Setup(std::move(platform_view),  //
                    engine_future.get(),       //
                    rasterizer_future.get(),   //
                    io_manager_future.get())   //
  ) {
    return nullptr;
  }

  return shell;
}

該方法的主要功能:

  • new Shell
  • GPU線程創(chuàng)建 rasterizer
  • 主線程創(chuàng)建 platform view
  • 創(chuàng)建 vsync_waiter
  • io線程中創(chuàng)建ShellIOManager對(duì)象
  • 創(chuàng)建Animator對(duì)象
  • ui線程中創(chuàng)建Engine對(duì)象
new Shell
Shell::Shell(DartVMRef vm, TaskRunners task_runners, Settings settings)
    : task_runners_(std::move(task_runners)),
      settings_(std::move(settings)),
      vm_(std::move(vm)),
      weak_factory_(this),
      weak_factory_gpu_(nullptr) {
  
  // Generate a WeakPtrFactory for use with the GPU thread. This does not need
  // to wait on a latch because it can only ever be used from the GPU thread
  // from this class, so we have ordering guarantees.
  fml::TaskRunner::RunNowOrPostTask(
      task_runners_.GetGPUTaskRunner(), fml::MakeCopyable([this]() mutable {
        this->weak_factory_gpu_ =
            std::make_unique<fml::WeakPtrFactory<Shell>>(this);
      }));

  // Install service protocol handlers.
  // 運(yùn)行在主線程帅掘,設(shè)置service protocol handlers
  service_protocol_handlers_[ServiceProtocol::kScreenshotExtensionName] = {
      task_runners_.GetGPUTaskRunner(),
      std::bind(&Shell::OnServiceProtocolScreenshot, this,
                std::placeholders::_1, std::placeholders::_2)};
  ...
}

創(chuàng)建Shell對(duì)象,成員變量task_runners_堂油、settings_以及vm_賦初值

PlatformViewAndroid

platform_view 的創(chuàng)建過程

platform_view_android.cc

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
          );
PlatformViewAndroid::PlatformViewAndroid(
    PlatformView::Delegate& delegate,
    flutter::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.";
}
AndroidSurface::Create
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
}

三種不同的AndroidSurface修档,目前android_surface_默認(rèn)數(shù)據(jù)類型為AndroidSurfaceGL

Engine初始化

engine.cc

Engine::Engine(Delegate& delegate,
               const PointerDataDispatcherMaker& dispatcher_maker,
               DartVM& vm,
               fml::RefPtr<const DartSnapshot> isolate_snapshot,
               TaskRunners task_runners,
               Settings settings,
               std::unique_ptr<Animator> animator,
               fml::WeakPtr<IOManager> io_manager,
               fml::RefPtr<SkiaUnrefQueue> unref_queue,
               fml::WeakPtr<SnapshotDelegate> snapshot_delegate)
    : delegate_(delegate),
      settings_(std::move(settings)),
      animator_(std::move(animator)),
      activity_running_(true),
      have_surface_(false),
      image_decoder_(task_runners,
                     vm.GetConcurrentWorkerTaskRunner(),
                     io_manager),
      task_runners_(std::move(task_runners)),
      weak_factory_(this) {
  // Runtime controller is initialized here because it takes a reference to this
  // object as its delegate. The delegate may be called in the constructor and
  // we want to be fully initilazed by that point.
  // 創(chuàng)建RuntimeController對(duì)象
  runtime_controller_ = std::make_unique<RuntimeController>(
      *this,                        // runtime delegate
      &vm,                          // VM
      std::move(isolate_snapshot),  // isolate snapshot
      task_runners_,                // task runners
      std::move(snapshot_delegate),
      std::move(io_manager),                 // io manager
      std::move(unref_queue),                // Skia unref queue
      image_decoder_.GetWeakPtr(),           // image decoder
      settings_.advisory_script_uri,         // advisory script uri
      settings_.advisory_script_entrypoint,  // advisory script entrypoint
      settings_.idle_notification_callback,  // idle notification callback
      settings_.isolate_create_callback,     // isolate create callback
      settings_.isolate_shutdown_callback,   // isolate shutdown callback
      settings_.persistent_isolate_data      // persistent isolate data
  );

  pointer_data_dispatcher_ = dispatcher_maker(*this);
}
RuntimeController

runtime_controller.cc

RuntimeController::RuntimeController(
    RuntimeDelegate& p_client,
    DartVM* p_vm,
    fml::RefPtr<const DartSnapshot> p_isolate_snapshot,
    fml::RefPtr<const DartSnapshot> p_shared_snapshot,
    TaskRunners p_task_runners,
    fml::WeakPtr<SnapshotDelegate> p_snapshot_delegate,
    fml::WeakPtr<IOManager> p_io_manager,
    std::string p_advisory_script_uri,
    std::string p_advisory_script_entrypoint,
    std::function<void(int64_t)> idle_notification_callback,
    WindowData p_window_data)
    : client_(p_client),
      vm_(p_vm),
      isolate_snapshot_(std::move(p_isolate_snapshot)),
      shared_snapshot_(std::move(p_shared_snapshot)),
      task_runners_(p_task_runners),
      snapshot_delegate_(p_snapshot_delegate),
      io_manager_(p_io_manager),
      advisory_script_uri_(p_advisory_script_uri),
      advisory_script_entrypoint_(p_advisory_script_entrypoint),
      idle_notification_callback_(idle_notification_callback),
      window_data_(std::move(p_window_data)),
      root_isolate_(
          //[見小節(jié)4.12.4]
          DartIsolate::CreateRootIsolate(vm_->GetVMData()->GetSettings(),
                                         isolate_snapshot_,
                                         shared_snapshot_,
                                         task_runners_,
                                         //[見小節(jié)4.12.3]
                                         std::make_unique<Window>(this),
                                         snapshot_delegate_,
                                         io_manager_,
                                         p_advisory_script_uri,
                                         p_advisory_script_entrypoint)) {
  std::shared_ptr<DartIsolate> root_isolate = root_isolate_.lock();
  root_isolate->SetReturnCodeCallback([this](uint32_t code) {
    root_isolate_return_code_ = {true, code};
  });
  if (auto* window = GetWindowIfAvailable()) {
    tonic::DartState::Scope scope(root_isolate);
    window->DidCreateIsolate();
    if (!FlushRuntimeStateToIsolate()) {
      FML_DLOG(ERROR) << "Could not setup intial isolate state.";
    }
  }
}
DartIsolate::CreateRootIsolate

dart_isolate.cc

std::weak_ptr<DartIsolate> DartIsolate::CreateRootIsolate(
    const Settings& settings,
    fml::RefPtr<const DartSnapshot> isolate_snapshot,
    fml::RefPtr<const DartSnapshot> shared_snapshot,
    TaskRunners task_runners,
    std::unique_ptr<Window> window,
    fml::WeakPtr<SnapshotDelegate> snapshot_delegate,
    fml::WeakPtr<IOManager> io_manager,
    std::string advisory_script_uri,
    std::string advisory_script_entrypoint,
    Dart_IsolateFlags* flags) {
  TRACE_EVENT0("flutter", "DartIsolate::CreateRootIsolate");
  Dart_Isolate vm_isolate = nullptr;
  std::weak_ptr<DartIsolate> embedder_isolate;

  //創(chuàng)建DartIsolate
  auto root_embedder_data = std::make_unique<std::shared_ptr<DartIsolate>>(
      std::make_shared<DartIsolate>(
          settings, std::move(isolate_snapshot),
          std::move(shared_snapshot), task_runners,                 
          std::move(snapshot_delegate), std::move(io_manager),        
          advisory_script_uri, advisory_script_entrypoint,    
          nullptr));
  //創(chuàng)建Isolate
  std::tie(vm_isolate, embedder_isolate) = CreateDartVMAndEmbedderObjectPair(
      advisory_script_uri.c_str(), advisory_script_entrypoint.c_str(),  
      nullptr, nullptr, flags,                               
      root_embedder_data.get(), true, &error);

  std::shared_ptr<DartIsolate> shared_embedder_isolate = embedder_isolate.lock();
  if (shared_embedder_isolate) {
    //只有root isolates能和window交互
    shared_embedder_isolate->SetWindow(std::move(window));
  }
  root_embedder_data.release();
  return embedder_isolate;
}

加載Dart代碼

FlutterActivityDelegate.runBundle

private void runBundle(String appBundlePath) {
    if (!this.flutterView.getFlutterNativeView().isApplicationRunning()) {
        FlutterRunArguments args = new FlutterRunArguments();
        ArrayList<String> bundlePaths = new ArrayList();
        ResourceUpdater resourceUpdater = FlutterMain.getResourceUpdater();
        if (resourceUpdater != null) {
            File patchFile = resourceUpdater.getInstalledPatch();
            JSONObject manifest = resourceUpdater.readManifest(patchFile);
            if (resourceUpdater.validateManifest(manifest)) {
                bundlePaths.add(patchFile.getPath());
            }
        }
        bundlePaths.add(appBundlePath);
        args.bundlePaths = (String[])bundlePaths.toArray(new String[0]);
        // 默認(rèn)是 main。 entrypoint 是指最終回調(diào)執(zhí)行的主函數(shù)名
        args.entrypoint = "main";
        this.flutterView.runFromBundle(args);
    }

}

runFromBundle

public void runFromBundle(FlutterRunArguments args) {
    ...
    this.mNativeView.runFromBundle(args);
    ...
}
public void runFromBundle(FlutterRunArguments args) {
        boolean hasBundlePaths = args.bundlePaths != null && args.bundlePaths.length != 0;
        ...
        if (hasBundlePaths) {
            this.runFromBundleInternal(args.bundlePaths, args.entrypoint, args.libraryPath);
        } else {
            this.runFromBundleInternal(new String[]{args.bundlePath, args.defaultPath}, args.entrypoint, args.libraryPath);
        }
    }

runFromBundleInternal

private void runFromBundleInternal(String[] bundlePaths, String entrypoint, String libraryPath) {
    ...
    this.mFlutterJNI.runBundleAndSnapshotFromLibrary(bundlePaths, entrypoint, libraryPath, this.mContext.getResources().getAssets());
    ...
}

runBundleAndSnapshotFromLibrary

    public void runBundleAndSnapshotFromLibrary(@NonNull String[] prioritizedBundlePaths, @Nullable String entrypointFunctionName, @Nullable String pathToEntrypointFunction, @NonNull AssetManager assetManager) {
        ...
        this.nativeRunBundleAndSnapshotFromLibrary(this.nativePlatformViewId, prioritizedBundlePaths, entrypointFunctionName, pathToEntrypointFunction, assetManager);
    }

nativeRunBundleAndSnapshotFromLibrary

nativeRunBundleAndSnapshotFromLibrary這是一個(gè)Native方法府框,簽名已介紹過萍悴,對(duì)應(yīng)的方法為RunBundleAndSnapshotFromLibrary。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末寓免,一起剝皮案震驚了整個(gè)濱河市癣诱,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌袜香,老刑警劉巖撕予,帶你破解...
    沈念sama閱讀 217,406評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異蜈首,居然都是意外死亡实抡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門欢策,熙熙樓的掌柜王于貴愁眉苦臉地迎上來吆寨,“玉大人,你說我怎么就攤上這事踩寇∽那澹” “怎么了?”我有些...
    開封第一講書人閱讀 163,711評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵俺孙,是天一觀的道長辣卒。 經(jīng)常有香客問我,道長睛榄,這世上最難降的妖魔是什么荣茫? 我笑而不...
    開封第一講書人閱讀 58,380評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮场靴,結(jié)果婚禮上啡莉,老公的妹妹穿的比我還像新娘。我一直安慰自己旨剥,他們只是感情好咧欣,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著泞边,像睡著了一般该押。 火紅的嫁衣襯著肌膚如雪疗杉。 梳的紋絲不亂的頭發(fā)上阵谚,一...
    開封第一講書人閱讀 51,301評(píng)論 1 301
  • 那天蚕礼,我揣著相機(jī)與錄音,去河邊找鬼梢什。 笑死奠蹬,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的嗡午。 我是一名探鬼主播囤躁,決...
    沈念sama閱讀 40,145評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼荔睹!你這毒婦竟也來了狸演?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,008評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤僻他,失蹤者是張志新(化名)和其女友劉穎宵距,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體吨拗,經(jīng)...
    沈念sama閱讀 45,443評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡满哪,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評(píng)論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了劝篷。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片哨鸭。...
    茶點(diǎn)故事閱讀 39,795評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖娇妓,靈堂內(nèi)的尸體忽然破棺而出像鸡,到底是詐尸還是另有隱情,我是刑警寧澤哈恰,帶...
    沈念sama閱讀 35,501評(píng)論 5 345
  • 正文 年R本政府宣布坟桅,位于F島的核電站,受9級(jí)特大地震影響蕊蝗,放射性物質(zhì)發(fā)生泄漏仅乓。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評(píng)論 3 328
  • 文/蒙蒙 一蓬戚、第九天 我趴在偏房一處隱蔽的房頂上張望夸楣。 院中可真熱鬧,春花似錦子漩、人聲如沸豫喧。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽紧显。三九已至,卻和暖如春缕棵,著一層夾襖步出監(jiān)牢的瞬間孵班,已是汗流浹背涉兽。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評(píng)論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留篙程,地道東北人枷畏。 一個(gè)月前我還...
    沈念sama閱讀 47,899評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像虱饿,于是被迫代替她去往敵國和親拥诡。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對(duì)...
    cosWriter閱讀 11,100評(píng)論 1 32
  • 今天基于Android分析下Flutter的啟動(dòng)流程氮发,首先看下官網(wǎng)提供的框架圖渴肉,最下面一層Embedder是特定的...
    juexingzhe閱讀 2,125評(píng)論 1 4
  • 一、Python簡介和環(huán)境搭建以及pip的安裝 4課時(shí)實(shí)驗(yàn)課主要內(nèi)容 【Python簡介】: Python 是一個(gè)...
    _小老虎_閱讀 5,744評(píng)論 0 10
  • 所有知識(shí)點(diǎn)已整理成app app下載地址 J2EE 部分: 1.Switch能否用string做參數(shù)爽冕? 在 Jav...
    侯蛋蛋_閱讀 2,432評(píng)論 1 4
  • 第一篇
    默哀一世閱讀 159評(píng)論 0 0