ps:flutter版本已經(jīng)更新到1.2.1
引入包
在build.gradle中可以找到這個(gè)
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
然后我們到該目錄下找到flutter.gradle
在該文件中可以找到
Path baseEnginePath = Paths.get(flutterRoot.absolutePath, "bin", "cache", "artifacts", "engine")
String targetArch = 'arm'
if (project.hasProperty('target-platform') &&
project.property('target-platform') == 'android-arm64') {
targetArch = 'arm64'
}
debugFlutterJar = baseEnginePath.resolve("android-${targetArch}").resolve("flutter.jar").toFile()
profileFlutterJar = baseEnginePath.resolve("android-${targetArch}-profile").resolve("flutter.jar").toFile()
releaseFlutterJar = baseEnginePath.resolve("android-${targetArch}-release").resolve("flutter.jar").toFile()
dynamicProfileFlutterJar = baseEnginePath.resolve("android-${targetArch}-dynamic-profile").resolve("flutter.jar").toFile()
dynamicReleaseFlutterJar = baseEnginePath.resolve("android-${targetArch}-dynamic-release").resolve("flutter.jar").toFile()
我們繼續(xù)查找目錄
這就是flutter.jar android部分編譯生成的包
在AS中直接看源碼的話只能找到編譯好的flutter.jar包中的.class文件穴豫,這里可以去github下載源碼
flutter內(nèi)核源碼:
https://github.com/flutter/engine/tree/45f69ac471b47e95dfeef36e5e81597b05ed19f5/shell/platform/android
OnCreate流程
flutter初始化分為4個(gè)部分:
FlutterMain、FlutterNativeView雏逾、FlutterView和Flutter Bundle的初始化
先看下Flutter初始化的時(shí)序圖(圖片來(lái)源于阿里咸魚(yú),自己就不獻(xiàn)丑了)
分析過(guò)android啟動(dòng)流程的話茬底,知道Application先于Activity執(zhí)行,在AndroidManifest.xml中可以找到FlutterApplication
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;
}
}
先看FlutterMain的初始化:
public class FlutterMain {
...
public static void startInitialization(Context applicationContext, 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;
//記錄初始化資源的起始時(shí)間
long initStartTimestampMillis = SystemClock.uptimeMillis();
initConfig(applicationContext);
initAot(applicationContext);
initResources(applicationContext);
//加載libflutter.so庫(kù)
if (sResourceUpdater == null) {
System.loadLibrary("flutter");
} else {
sResourceExtractor.waitForCompletion();
File lib = new File(PathUtils.getDataDirectory(applicationContext), DEFAULT_LIBRARY);
if (lib.exists()) {
System.load(lib.getAbsolutePath());
} else {
System.loadLibrary("flutter");
}
}
//初始化完成時(shí)間
long initTimeMillis = SystemClock.uptimeMillis() - initStartTimestampMillis;
nativeRecordStartTimestamp(initTimeMillis);
}
}
接下來(lái)看一下MainActivity卷中,繼承自FlutterActivity,找到其的onCreate方法
public class FlutterActivity extends Activity implements FlutterView.Provider, PluginRegistry, ViewFactory {
private final FlutterActivityDelegate delegate = new FlutterActivityDelegate(this, this);
private final FlutterActivityEvents eventDelegate = delegate;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
eventDelegate.onCreate(savedInstanceState);
}
}
實(shí)際上調(diào)用的是FlutterActivityDelegate的onCreate方法
public final class FlutterActivityDelegate
implements FlutterActivityEvents,
FlutterView.Provider,
PluginRegistry {
@Override
public void onCreate(Bundle savedInstanceState) {
//sdk版本大于21篙耗,即5.0,和沉浸式狀態(tài)欄有關(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);
}
String[] args = getArgsFromIntent(activity.getIntent());
// 1.
FlutterMain.ensureInitializationComplete(activity.getApplicationContext(), args);
flutterView = viewFactory.createFlutterView(activity);
//flutterView默認(rèn)的創(chuàng)建結(jié)果是null欲主,必然進(jìn)入
if (flutterView == null) {
FlutterNativeView nativeView = viewFactory.createFlutterNativeView();
// 2.
flutterView = new FlutterView(activity, null, nativeView);
//界面置為全屏
flutterView.setLayoutParams(matchParent);
//flutterView為顯示的主界面
activity.setContentView(flutterView);
launchView = createLaunchView();
if (launchView != null) {
addLaunchView();
}
}
if (loadIntent(activity.getIntent())) {
return;
}
String appBundlePath = FlutterMain.findAppBundlePath(activity.getApplicationContext());
if (appBundlePath != null) {
//3.
runBundle(appBundlePath);
}
}
}
assets資源已經(jīng)初始化完畢,將資源路徑傳遞給native端進(jìn)行處理
public class FlutterMain {
public static void ensureInitializationComplete(Context applicationContext, String[] args) {
...
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;
...
}
}
然后看下FlutterView是個(gè)什么
public class FlutterView extends SurfaceView implements BinaryMessenger, TextureRegistry {
...
public FlutterView(Context context, AttributeSet attrs, FlutterNativeView nativeView) {
super(context, attrs);
Activity activity = (Activity) getContext();
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);
sendLocalesToDart(getResources().getConfiguration());
sendUserPlatformSettingsToDart();
}
...
}
FlutterView是一個(gè)SurfaceView贿讹,那么再看其surfaceCreated方法,調(diào)用的是FlutterJNI中的native方法
@UiThread
public void onSurfaceCreated(@NonNull Surface surface) {
ensureAttachedToNative();
nativeSurfaceCreated(nativePlatformViewId, surface);
}
private native void nativeSurfaceCreated(long nativePlatformViewId, Surface surface);
也即是說(shuō)flutter其實(shí)是自己繪制面殖,然后在surfaceview上顯示的,稍微深入一下來(lái)驗(yàn)證一下:
來(lái)找一下這個(gè)native方法,看一下里面到底做了什么,來(lái)到platform_view_android_jni.cc文件下(路徑:engine/shell/platform/android/io/platform_view_android_jni.cc)
//platform_view_android_jni.cc
static const JNINativeMethod flutter_jni_methods[] = {
...
{
.name = "nativeSurfaceCreated",
.signature = "(JLandroid/view/Surface;)V",
.fnPtr = reinterpret_cast<void*>(&shell::SurfaceCreated),
},
...
}
這是jni中動(dòng)態(tài)注冊(cè)的方式,nativeSurfaceCreated對(duì)應(yīng)了SurfaceCreated方法
//platform_view_android_jni.cc
static void SurfaceCreated(JNIEnv* env,
jobject jcaller,
jlong shell_holder,
jobject jsurface) {
fml::jni::ScopedJavaLocalFrame scoped_local_reference_frame(env);
//創(chuàng)建新的窗口用于顯示
auto window = fml::MakeRefCounted<AndroidNativeWindow>(
ANativeWindow_fromSurface(env, jsurface));
ANDROID_SHELL_HOLDER->GetPlatformView()->NotifyCreated(std::move(window));
}
通過(guò)ANativeWindow與surfaceView進(jìn)行綁定荣病,再看NotifyCreated方法
//platform_view_android.cc
void PlatformViewAndroid::NotifyCreated(
fml::RefPtr<AndroidNativeWindow> native_window) {
if (android_surface_) {
InstallFirstFrameCallback();
android_surface_->SetNativeWindow(native_window);
}
PlatformView::NotifyCreated();
}
SetNativeWindow(native_window)與我們的window相關(guān)脖岛,繼續(xù)追蹤,因android_surface_是一個(gè)std::unique_ptr<AndroidSurface>(ptr是動(dòng)態(tài)指針,即AndroidSurface類型)
//android_surface.h
class AndroidSurface {
public:
static std::unique_ptr<AndroidSurface> Create(bool use_software_rendering);
...
virtual bool SetNativeWindow(fml::RefPtr<AndroidNativeWindow> window) = 0;
};
}
我們找其方法實(shí)現(xiàn)的類
//android_surface_gi.cc
bool AndroidSurfaceGL::SetNativeWindow(
fml::RefPtr<AndroidNativeWindow> window) {
onscreen_context_ = nullptr;
if (!offscreen_context_ || !offscreen_context_->IsValid()) {
return false;
}
// Create the onscreen context.
onscreen_context_ = fml::MakeRefCounted<AndroidContextGL>(
offscreen_context_->Environment(),
offscreen_context_.get() );
if (!onscreen_context_->IsValid()) {
onscreen_context_ = nullptr;
return false;
}
if (!onscreen_context_->CreateWindowSurface(std::move(window))) {
onscreen_context_ = nullptr;
return false;
}
return true;
}
一切相關(guān)的信息都在CreateWindowSurface中
//android_context_gi.cc
bool AndroidContextGL::CreateWindowSurface(
fml::RefPtr<AndroidNativeWindow> window) {
window_ = std::move(window);
EGLDisplay display = environment_->Display();
const EGLint attribs[] = {EGL_NONE};
//創(chuàng)建一個(gè)通用的surface
surface_ = eglCreateWindowSurface(
display, config_,
reinterpret_cast<EGLNativeWindowType>(window_->handle()), attribs);
return surface_ != EGL_NO_SURFACE;
}
到這一步基本追蹤完了霸奕,通過(guò)egl創(chuàng)建了一個(gè)surface_(EGLSurface)供c端使用
繪制
還記得之前在自定義控件是我們繪制圓形時(shí)使用的方法嗎适揉?
canvas.drawCircle(Offset(0, 0), 100, _paint);
深入源碼一下
void drawCircle(Offset c, double radius, Paint paint) {
assert(_offsetIsValid(c));
assert(paint != null);
_drawCircle(c.dx, c.dy, radius, paint._objects, paint._data);
}
void _drawCircle(double x,
double y,
double radius,
List<dynamic> paintObjects,
ByteData paintData) native 'Canvas_drawCircle';
這里也使用了native方法,即dart調(diào)用c語(yǔ)言汤善,我們也來(lái)找一下它的源碼簡(jiǎn)單分析一下
Canvas_drawCircle
降铸,和jni的命名不同桶蝎,這個(gè)是表示在Canvas類中的drawCircle方法
其實(shí)dart.ui包就在engine中,painting.dart文件也在其中
在canvas.cc(路徑:engine/lib/ui/painting/canvas.cc)文件中找到drawCircle方法
//canvas.cc
void Canvas::drawCircle(double x,
double y,
double radius,
const Paint& paint,
const PaintData& paint_data) {
if (!canvas_)
return;
canvas_->drawCircle(x, y, radius, *paint.paint());
}
canvas_是一個(gè)SkCanvas*
//canvas.h
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/utils/SkShadowUtils.h"
class Canvas : public RefCountedDartWrappable<Canvas> {
...
private:
explicit Canvas(SkCanvas* canvas);
SkPictureRecorder::beginRecording,
SkCanvas* canvas_;
};
SkCanvas.h在engine工程中無(wú)法找到仇味,不過(guò)我們能在github的skia工程中找到
void SkCanvas::drawCircle(SkScalar cx, SkScalar cy, SkScalar radius,
const SkPaint& paint) {
if (radius < 0) {
radius = 0;
}
SkRect r;
r.set(cx - radius, cy - radius, cx + radius, cy + radius);
this->drawOval(r, paint);
}
到這就不再分析下去了贩挣,flutter是通過(guò)skia引擎直接渲染的,所以在繪制速度上要比原生還快些
互調(diào)接口
- AndroidView 來(lái)調(diào)用android原生的控件(Ios使用 UiKitView)
目前還存在一些bug疯溺,感興趣的可以查看一下flutter_webview_plugin開(kāi)源庫(kù)的實(shí)現(xiàn)源碼 - EventChannel 傳遞和接收事件流
MethodChannel 傳遞和接收方法
BasicMessageChannel 傳遞和接收字符串
相關(guān)文章