美文网首页Flutter
Flutter笔记-flutter与android的互调

Flutter笔记-flutter与android的互调

作者: 叶落清秋 | 来源:发表于2019-03-26 15:17 被阅读0次

    ps:flutter版本已经更新到1.2.1

    引入包

    在build.gradle中可以找到这个

    apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.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()
    

    我们继续查找目录


    flutter.jar

    这就是flutter.jar android部分编译生成的包

    在AS中直接看源码的话只能找到编译好的flutter.jar包中的.class文件,这里可以去github下载源码
    flutter内核源码:
    https://github.com/flutter/engine/tree/45f69ac471b47e95dfeef36e5e81597b05ed19f5/shell/platform/android

    OnCreate流程

    flutter初始化分为4个部分:
    FlutterMain、FlutterNativeView、FlutterView和Flutter Bundle的初始化
    先看下Flutter初始化的时序图(图片来源于阿里咸鱼,自己就不献丑了)


    时序图

    分析过android启动流程的话,知道Application先于Activity执行,在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;
            //记录初始化资源的起始时间
            long initStartTimestampMillis = SystemClock.uptimeMillis();
            initConfig(applicationContext);
            initAot(applicationContext);
            initResources(applicationContext);
            //加载libflutter.so库
            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");
                }
            }
            //初始化完成时间
            long initTimeMillis = SystemClock.uptimeMillis() - initStartTimestampMillis;
            nativeRecordStartTimestamp(initTimeMillis);
        }
    }
    

    接下来看一下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);
        }
    }
    

    实际上调用的是FlutterActivityDelegate的onCreate方法

    public final class FlutterActivityDelegate
            implements FlutterActivityEvents,
                       FlutterView.Provider,
                       PluginRegistry {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            //sdk版本大于21,即5.0,和沉浸式状态栏有关
            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默认的创建结果是null,必然进入
            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资源已经初始化完毕,将资源路径传递给native端进行处理

    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是个什么

    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是一个SurfaceView,那么再看其surfaceCreated方法,调用的是FlutterJNI中的native方法

      @UiThread
      public void onSurfaceCreated(@NonNull Surface surface) {
        ensureAttachedToNative();
        nativeSurfaceCreated(nativePlatformViewId, surface);
      }
    
      private native void nativeSurfaceCreated(long nativePlatformViewId, Surface surface);
    

    也即是说flutter其实是自己绘制,然后在surfaceview上显示的,稍微深入一下来验证一下:
    来找一下这个native方法,看一下里面到底做了什么,来到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中动态注册的方式,nativeSurfaceCreated对应了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);
      //创建新的窗口用于显示
      auto window = fml::MakeRefCounted<AndroidNativeWindow>(
          ANativeWindow_fromSurface(env, jsurface));
      ANDROID_SHELL_HOLDER->GetPlatformView()->NotifyCreated(std::move(window));
    }
    

    通过ANativeWindow与surfaceView进行绑定,再看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相关,继续追踪,因android_surface_是一个std::unique_ptr<AndroidSurface>(ptr是动态指针,即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;
    };
    } 
    

    我们找其方法实现的类

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

    一切相关的信息都在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};
      //创建一个通用的surface
      surface_ = eglCreateWindowSurface(
          display, config_,
          reinterpret_cast<EGLNativeWindowType>(window_->handle()), attribs);
      return surface_ != EGL_NO_SURFACE;
    }
    

    到这一步基本追踪完了,通过egl创建了一个surface_(EGLSurface)供c端使用

    绘制

    还记得之前在自定义控件是我们绘制圆形时使用的方法吗?

    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调用c语言,我们也来找一下它的源码简单分析一下
    Canvas_drawCircle,和jni的命名不同,这个是表示在Canvas类中的drawCircle方法
    其实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_是一个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工程中无法找到,不过我们能在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是通过skia引擎直接渲染的,所以在绘制速度上要比原生还快些

    互调接口

    1. AndroidView 来调用android原生的控件(Ios使用 UiKitView)
      目前还存在一些bug,感兴趣的可以查看一下flutter_webview_plugin开源库的实现源码
    2. EventChannel 传递和接收事件流
      MethodChannel 传递和接收方法
      BasicMessageChannel 传递和接收字符串

    相关文章

    1. 深入理解Flutter Platform Channel
    2. Flutter Platform channel详解
    3. 在Flutter中嵌入Native组件的正确姿势是
    4. Flutter之在Flutter布局中嵌入原生组件Android篇

    相关文章

      网友评论

        本文标题:Flutter笔记-flutter与android的互调

        本文链接:https://www.haomeiwen.com/subject/oabzmqtx.html