Flutter 原始碼剖析(一)

程式設計之路從0到1發表於2019-09-07

前言

做技術,只有弄懂了原理,才能遇事不慌,手中無碼,心中有碼。這篇文章主要研究Flutter 在安卓平臺上的啟動流程原始碼。

啟動流程

入口Activity

當我們建立一個Flutter app工程時,開啟android目錄下的原始碼,會發現有一個MainActivity繼承自FlutterActivity,整個MainActivity非常簡單,只在onCreate下加了一行程式碼GeneratedPluginRegistrant.registerWith(this),那麼FlutterActivity又是何方神聖呢?FlutterActivity的原始碼在Flutter SDK的jar包中,想要研究Flutter原始碼,第一件事就是需要下載一套SDK原始碼,我們可以在GitHub上下載 engine原始碼

public class MainActivity extends FlutterActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GeneratedPluginRegistrant.registerWith(this);
  }
}
複製程式碼

engine\src\flutter\shell\platform\android\io\flutter\app\FlutterActivity.java 省略部分原始碼,刪除註釋後程式碼如下

public class FlutterActivity extends Activity implements 
FlutterView.Provider, PluginRegistry, ViewFactory {
    private static final String TAG = "FlutterActivity";
    
    private final FlutterActivityDelegate delegate = new FlutterActivityDelegate(this, this);

    private final FlutterActivityEvents eventDelegate = delegate;
    private final FlutterView.Provider viewProvider = delegate;
    private final PluginRegistry pluginRegistry = delegate;

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

    @Override
    protected void onStart() {
        super.onStart();
        eventDelegate.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        eventDelegate.onResume();
    }

    @Override
    protected void onDestroy() {
        eventDelegate.onDestroy();
        super.onDestroy();
    }

   // ...省略部分原始碼...
}
複製程式碼

可以看到FlutterActivity繼承自Activity,並實現了三個介面,FlutterActivity的生命週期方法,均由一個代理類FlutterActivityDelegate處理。

engine\src\flutter\shell\platform\android\io\flutter\app\FlutterActivityDelegate.java

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // 根據當前系統版本設定沉浸式狀態列
        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傳入的引數資訊
        String[] args = getArgsFromIntent(activity.getIntent());
        // 初始化一些引數配置資訊,包括打包的flutter程式碼路徑、應用儲存目錄、引擎快取目錄等
        FlutterMain.ensureInitializationComplete(activity.getApplicationContext(), args);
        
        flutterView = viewFactory.createFlutterView(activity);
        // 真正建立contentView的地方
        if (flutterView == null) {
            FlutterNativeView nativeView = viewFactory.createFlutterNativeView();
            flutterView = new FlutterView(activity, null, nativeView);
            flutterView.setLayoutParams(matchParent);
            activity.setContentView(flutterView);
            launchView = createLaunchView();
            if (launchView != null) {
                addLaunchView();
            }
        }

        if (loadIntent(activity.getIntent())) {
            return;
        }

        String appBundlePath = FlutterMain.findAppBundlePath(activity.getApplicationContext());
        if (appBundlePath != null) {
            runBundle(appBundlePath);
        }
    }
複製程式碼

我們自然是要找到onCreate方法,以上程式碼我增加了一點註釋,我們要快速定位到關鍵程式碼,什麼是關鍵程式碼,看到了activity.setContentView(flutterView);,這裡就是關鍵程式碼,終於見到了我們熟悉的setContentView了。這裡我們不禁要問,這個flutterView到底是個什麼View?

一開始我們就知道ViewFactoryFlutterActivity實現的,這裡createFlutterView方法實現也在FlutterActivity裡,但這個方法始終返回空,再看createFlutterNativeView方法,仍然是返回空

    @Override
    public FlutterNativeView createFlutterNativeView() {
        return null;
    }
    
    @Override
    public FlutterNativeView createFlutterNativeView() {
        return null;
    }
複製程式碼

這裡真正的flutterView實際上是通過flutterView = new FlutterView(activity, null, nativeView)這行程式碼new出來的,然後傳遞給setContentView

接下來直接看到FlutterView原始碼(省略部分程式碼)

public class FlutterView extends SurfaceView implements BinaryMessenger, TextureRegistry {
    private static final String TAG = "FlutterView";

    public FlutterView(Context context, AttributeSet attrs, FlutterNativeView nativeView) {
        super(context, attrs);

        Activity activity = getActivity(getContext());
        if (activity == null) {
            throw new IllegalArgumentException("Bad context");
        }

        if (nativeView == null) {
            mNativeView = new FlutterNativeView(activity.getApplicationContext());
        } else {
            mNativeView = nativeView;
        }

        dartExecutor = mNativeView.getDartExecutor();
        flutterRenderer = new FlutterRenderer(mNativeView.getFlutterJNI());
        mIsSoftwareRenderingEnabled = FlutterJNI.nativeGetIsSoftwareRenderingEnabled();
        mMetrics = new ViewportMetrics();
        mMetrics.devicePixelRatio = context.getResources().getDisplayMetrics().density;
        setFocusable(true);
        setFocusableInTouchMode(true);

        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();
            }
        };
        getHolder().addCallback(mSurfaceCallback);

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

        // Create all platform channels
        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);

        // Create and setup plugins
        PlatformPlugin platformPlugin = new PlatformPlugin(activity, platformChannel);
        addActivityLifecycleListener(platformPlugin);
        mImm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        mTextInputPlugin = new TextInputPlugin(this, dartExecutor);
        androidKeyProcessor = new AndroidKeyProcessor(keyEventChannel, mTextInputPlugin);
        androidTouchProcessor = new AndroidTouchProcessor(flutterRenderer);

        // Send initial platform information to Dart
        sendLocalesToDart(getResources().getConfiguration());
        sendUserPlatformSettingsToDart();
    }
複製程式碼

到這裡就明白了,FlutterView實際上就是安卓中的SurfaceView,因為SurfaceView是雙緩衝的,可以在子執行緒更新UI,效能高效,因此通常是用來做遊戲開發、視訊直播。經過簡單的原始碼分析,我們大致能明白Flutter在安卓上的實現方式,整個Flutter開發的app都是在一個Activity中進行渲染的,這就有點像現在前端流行的所謂單頁應用。

還個方法中還建立了各種平臺外掛和platform channel,用於Flutter層和原生程式碼之間的資料傳遞。

環境初始化

現在我們再回過頭來看一下剛剛漏過的一些程式碼,看看它們做了些什麼事 onCreate函式中有呼叫FlutterMain.ensureInitializationComplete(activity.getApplicationContext(), args)

    /**
     * Blocks until initialization of the native system has completed.
     */
    public static void ensureInitializationComplete(@NonNull Context applicationContext, @Nullable String[] args) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
          throw new IllegalStateException("ensureInitializationComplete must be called on the main thread");
        }
        if (sSettings == null) {
          throw new IllegalStateException("ensureInitializationComplete must be called after startInitialization");
        }
        if (sInitialized) {
            return;
        }
        try {
            sResourceExtractor.waitForCompletion();

            List<String> shellArgs = new ArrayList<>();
            shellArgs.add("--icu-symbol-prefix=_binary_icudtl_dat");

            ApplicationInfo applicationInfo = getApplicationInfo(applicationContext);
            shellArgs.add("--icu-native-lib-path=" + applicationInfo.nativeLibraryDir + File.separator + DEFAULT_LIBRARY);

           // ...省略...

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

            String appBundlePath = findAppBundlePath(applicationContext);
            String appStoragePath = PathUtils.getFilesDir(applicationContext);
            String engineCachesPath = PathUtils.getCacheDirectory(applicationContext);
            nativeInit(applicationContext, shellArgs.toArray(new String[0]),
                appBundlePath, appStoragePath, engineCachesPath);

            sInitialized = true;
        } catch (Exception e) {
            Log.e(TAG, "Flutter initialization failed.", e);
            throw new RuntimeException(e);
        }
    }
複製程式碼

該方法註釋已經明確告訴我們,這是一個阻塞的方法,直到底層初始化完成。這意味著該方法執行會影響app的啟動速度。總的來說,該方法做了幾件事,它保證初始化操作在主執行緒執行,呼叫sResourceExtractor.waitForCompletion()完成資原始檔的提取工作,拼接所有相關的shellArgs引數,包括intent中的引數,配置dart程式碼編譯產物appBundle路徑,應用儲存、引擎快取目錄等資訊, 最後通過執行nativeInit函式在c++層初始化這些資訊

建立 splash view

接下來,還有一個地方值得一說,在建立FlutterView之後,呼叫了一個createLaunchView方法

    private View createLaunchView() {
        if (!showSplashScreenUntilFirstFrame()) {
            return null;
        }
        final Drawable launchScreenDrawable = getLaunchScreenDrawableFromActivityTheme();
        if (launchScreenDrawable == null) {
            return null;
        }
        final View view = new View(activity);
        view.setLayoutParams(matchParent);
        view.setBackground(launchScreenDrawable);
        return view;
    }
複製程式碼

這個方法,其實就是在Flutter啟動後新增一個splash view。大家知道,在Flutter應用啟動之後,會有一小段白屏的時間,之所以會白屏,就是這個方法導致的。目前的解決辦法,就是手動新增一個設計好的閃屏頁,平滑的過度一下。那麼如何修改預設的白屏頁,設定我們自己的splash view呢?

    private Drawable getLaunchScreenDrawableFromActivityTheme() {
        TypedValue typedValue = new TypedValue();
        if (!activity.getTheme().resolveAttribute(
            android.R.attr.windowBackground,
            typedValue,
            true)) {
            return null;
        }
        if (typedValue.resourceId == 0) {
            return null;
        }
        try {
            return activity.getResources().getDrawable(typedValue.resourceId);
        } catch (NotFoundException e) {
            Log.e(TAG, "Referenced launch screen windowBackground resource does not exist");
            return null;
        }
    }
複製程式碼

可以看到,這個Drawable其實是從主題的windowBackground中取的,我們開啟app工程中的styles.xml

    <style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
        <!-- Show a splash screen on the activity. Automatically removed when Flutter draws its first frame -->
        <item name="android:windowBackground">@drawable/launch_background</item>
    </style>
複製程式碼

看到,windowBackground其實是指定為launch_background,在drawable資料夾下找到它

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@android:color/white" />

    <!-- You can insert your own image assets here -->
    <!-- <item>
        <bitmap
            android:gravity="center"
            android:src="@mipmap/launch_image" />
    </item> -->
</layer-list>
複製程式碼

這裡預設背景確實被設定成了白色,並且還友好的給出了一個設定圖片的示例,將註釋的程式碼開啟,就可以設定自己的splash view

Application啟動

我們知道安卓app啟動時,首先呼叫的是ApplicationonCreate,現在來看一看Flutter應用的Application做了些什麼 flutter\shell\platform\android\io\flutter\app\FlutterApplication.java

public class FlutterApplication extends Application {
    @Override
    @CallSuper
    public void onCreate() {
        super.onCreate();
        FlutterMain.startInitialization(this);
    }

    private Activity mCurrentActivity = null;
    public Activity getCurrentActivity() {
        return mCurrentActivity;
    }
    public void setCurrentActivity(Activity mCurrentActivity) {
        this.mCurrentActivity = mCurrentActivity;
    }
}
複製程式碼

整個FlutterApplication比較簡單,主要呼叫了FlutterMain.startInitialization(this)開啟初始化

    public static void startInitialization(@NonNull Context applicationContext, @NonNull Settings settings) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
          throw new IllegalStateException("startInitialization must be called on the main thread");
        }
        // Do not run startInitialization more than once.
        if (sSettings != null) {
          return;
        }

        sSettings = settings;

        long initStartTimestampMillis = SystemClock.uptimeMillis();
        initConfig(applicationContext);
        initAot(applicationContext);
        initResources(applicationContext);

        System.loadLibrary("flutter");
        long initTimeMillis = SystemClock.uptimeMillis() - initStartTimestampMillis;
        nativeRecordStartTimestamp(initTimeMillis);
    }
複製程式碼

該方法註釋表明,它是用來初始化底層的Flutter 引擎的,主要做了幾件事,

  • 初始化配置
  • 獲取是否預編譯模式
  • 初始化並提取資原始檔
  • 載入libflutter.so

Java層與Flutter引擎關聯

FlutterApplication中載入了引擎的so,我們不禁要問,那Flutter引擎又是在哪建立的,怎麼與原生Java程式碼關聯起來的呢?

FlutterView構造方法中建立了FlutterNativeView,看到FlutterNativeView的構造方法

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

在這裡主要建立了FlutterJNI物件,並呼叫了一個關鍵方法attach,一路跟蹤該方法呼叫

    private void attach(FlutterNativeView view, boolean isBackgroundView) {
        mFlutterJNI.attachToNative(isBackgroundView);
        dartExecutor.onAttachedToJNI();
    }
複製程式碼

flutter\shell\platform\android\io\flutter\embedding\engine\FlutterJNI.java

  public void attachToNative(boolean isBackgroundView) {
    ensureRunningOnMainThread();
    ensureNotAttachedToNative();
    nativePlatformViewId = nativeAttach(this, isBackgroundView);
  }
  
  private native long nativeAttach(FlutterJNI flutterJNI, boolean isBackgroundView);
複製程式碼

最後發現呼叫了一個native方法,並將FlutterJNI例項物件自身傳入了C++層。這裡,我們怎麼才能找到native方法所對應的C++原始碼呢?

我這裡就介紹一種最簡單的傻瓜式方法,不需要太多技巧,大家可以下載一個FileLocatorPro工具,它是Windows平臺上的文字搜尋神器,建議最好安裝一個。

在這裡插入圖片描述
為了搜尋更快,我們不僅僅將下載的Flutter engine原始碼根路徑設定進去,還要縮寫一點範圍,我這裡將原始碼根目錄下的flutter\shell\platform\android設定為搜尋路徑,另外還可以在檔名稱一欄填入*.cc,表示僅搜尋以.cc作為字尾的檔案,這裡.cc是C++原始檔字尾名。最後我們秒搜到了匹配的內容

flutter\shell\platform\android\platform_view_android_jni.cc

static const JNINativeMethod flutter_jni_methods[] = {
      // Start of methods from FlutterNativeView
      {
          .name = "nativeAttach",
          .signature = "(Lio/flutter/embedding/engine/FlutterJNI;Z)J",
          .fnPtr = reinterpret_cast<void*>(&AttachJNI),
      }
複製程式碼

這是一個結構體陣列,可以看到nativeAttach對應的函式指標是AttachJNI,我們繼續在當前檔案中找到AttachJNI函式,它就是Java層nativeAttach方法的具體實現

// Called By Java
static jlong AttachJNI(JNIEnv* env,
                       jclass clazz,
                       jobject flutterJNI,
                       jboolean is_background_view) {
  fml::jni::JavaObjectWeakGlobalRef java_object(env, flutterJNI);
  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;
  }
}
複製程式碼

這裡的C++程式碼主要乾了一件事,就是通過make_unique來建立了一個AndroidShellHolder物件,因此我們需要找到AndroidShellHolder類的構造方法

flutter/shell/platform/android/android_shell_holder.cc

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++);

  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};
  }

  // ...省略...

  // The current thread will be used as the platform thread. Ensure that the
  // message loop is initialized.
  fml::MessageLoop::EnsureInitializedForCurrentThread();
  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) {
    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_.gpu_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,       // gpu
                                    ui_runner,        // ui
                                    io_runner         // io
  );

  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;

  // ...省略...
}
複製程式碼

這個方法裡面程式碼比較多,省略部分程式碼,我們看到最重要的幾個地方,首先這裡有四個執行緒,除了當前執行緒作為platform執行緒,還建立了三個新的執行緒

  • gpu執行緒
  • ui執行緒
  • io執行緒

此處當配圖,來自閒魚技術部落格

在這裡插入圖片描述

四個執行緒分別持有一個TaskRunner物件,後續會通過這些TaskRunner來將一些操作放到對應的執行緒中去執行。

  • Platform Task Runner的執行緒可以理解為是主執行緒,它不僅僅處理與Engine互動,它還處理來自平臺的訊息。

  • UI Task Runner被用於執行Dart root isolate程式碼,簡單說也就是Dart語言的主執行緒。我們所編寫的Dart程式碼基本就是在這個執行緒執行。因此該執行緒繁忙會導致UI卡頓,如果有繁重的計算任務,如加密、解壓縮等,應當在Dart中另起一個isolate來執行程式碼。需要注意,另啟的isolate是不能與Flutter引擎互動的,表現在開發中,也就是不能在新建立的isolate中呼叫外掛,例如在新的isolate操作SQlite資料庫,如有這種需求,可以使用FlutterIsolate 庫

  • GPU Task Runner 用於執行裝置GPU的相關呼叫。主要是配置管理每一幀繪製所需要的GPU資源。如果該執行緒卡頓,直接導致程式卡頓。通常來說用平臺程式碼和Dart程式碼都無法直接操作到該執行緒

  • IO Runner的主要是從圖片儲存(如磁碟)中讀取壓縮的圖片格式,將圖片資料進行處理,為GPU Runner的渲染做好準備。也就是處理與磁碟IO相關的事務

最後,看到以下函式的呼叫,此處即是建立引擎的地方

shell_ =
      Shell::Create(task_runners,             // task runners
                    settings_,                // settings
                    on_create_platform_view,  // platform view create callback
                    on_create_rasterizer      // rasterizer create callback
      );
複製程式碼

大家有興趣可以找相關原始碼,繼續跟蹤一下原始碼,看看引擎是如何建立的

\flutter\shell\common\shell.cc
複製程式碼

執行Dart程式碼

通過反編譯Flutter生成的apk,我們很清楚的知道,Dart程式碼編譯後的產物,包括相關的資原始檔,實際上都是打包到安卓的assets目錄下的,那麼Dart程式碼是在哪載入執行的呢?

FlutterActivityDelegateonCreate方法的最後有如下程式碼

 String appBundlePath = FlutterMain.findAppBundlePath(activity.getApplicationContext());
 if (appBundlePath != null) {
     runBundle(appBundlePath);
 }
複製程式碼

這裡首先獲取資原始檔提取後在應用所屬目錄下的路徑,然後呼叫runBundle進行載入執行。runBundle方法最終呼叫FlutterJNI中的一個native方法

  private native void nativeRunBundleAndSnapshotFromLibrary(
      long nativePlatformViewId,
      @NonNull String[] prioritizedBundlePaths,
      @Nullable String entrypointFunctionName,
      @Nullable String pathToEntrypointFunction,
      @NonNull AssetManager manager
  );
複製程式碼

呼叫過程如下,點選大圖

在這裡插入圖片描述

總結

  • FlutterActivityDelegateonCreate流程圖
    在這裡插入圖片描述
    物件呼叫關係圖,點選大圖
    在這裡插入圖片描述

FlutterMain.ensureInitializationComplete方法呼叫

在這裡插入圖片描述

FlutterNativeView

歡迎關注我的公眾號:程式設計之路從0到1

程式設計之路從0到1

相關文章