了解了Flutter的Widget以及Flutter的渲染,突然有新的问题的产生,Flutter如果要和Native进行混合开发,就会产生新的问题,——混合栈管理。
比如Flutter要回退到原生界面,原生界面应该如何感知呢,原生界面进入Flutter界面又要怎么通知Native。
根据源码加图片来看下Flutter怎么在Android启动
Flutter出现的目的旨在统一Android/IOS两端编程,因此完全基于Flutter开发的App,只需提供一个包含FlutterView的页面,后续页面增加/删除/跳转均在FlutterView的Navigator中进行管理。
直接公布最合适的方案
抽取单一FlutterView或FlutterNativeView,后续每启动一个Activity都对FlutterView或FlutterNativeView进行复用
对比RN,native与rn混合开发,是有一个reactActivity,用layoutInspector看下Flutter层面
可以看到flutter基于自身去渲染
接下来用源码看戏FlutterActivity都做了什么操作
public class FlutterActivity extends Activity implements Provider, PluginRegistry, ViewFactory {
private final FlutterActivityDelegate delegate = new FlutterActivityDelegate(this, this);//1
private final FlutterActivityEvents eventDelegate;//1
private final Provider viewProvider;
private final PluginRegistry pluginRegistry;//2
public FlutterActivity() {
this.eventDelegate = this.delegate;
this.viewProvider = this.delegate;
this.pluginRegistry = this.delegate;
}
…………
}
看下构造函数
2.pluginRegistry主要用于原生方法注册通信的,封装一些方法,相当于给Flutter增加插件
1.FlutterActivityEvents是一个接口,具体实现类是FlutterActivityDelegate 给FlutterView发送当前app处于的状态,包括内存和生命周期,上下文,以及intent
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.eventDelegate.onCreate(savedInstanceState);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
this.eventDelegate.onConfigurationChanged(newConfig);
}
protected void onPostResume() {
super.onPostResume();
this.eventDelegate.onPostResume();
}
…………
1.我们知道当走到Activity的onCreate时,会执行Delegate的onCreate
public FlutterActivityDelegate(Activity activity, FlutterActivityDelegate.ViewFactory viewFactory) {
this.activity = (Activity)Preconditions.checkNotNull(activity);
this.viewFactory = (FlutterActivityDelegate.ViewFactory)Preconditions.checkNotNull(viewFactory);
}
public void onCreate(Bundle savedInstanceState) {
if (VERSION.SDK_INT >= 21) {
Window window = this.activity.getWindow();
window.addFlags(-2147483648);
window.setStatusBarColor(1073741824);
window.getDecorView().setSystemUiVisibility(1280);
}
String[] args = getArgsFromIntent(this.activity.getIntent());
FlutterMain.ensureInitializationComplete(this.activity.getApplicationContext(), args);
this.flutterView = this.viewFactory.createFlutterView(this.activity);
if (this.flutterView == null) {
FlutterNativeView nativeView = this.viewFactory.createFlutterNativeView();
this.flutterView = new FlutterView(this.activity, (AttributeSet)null, nativeView);
this.flutterView.setLayoutParams(matchParent);
this.activity.setContentView(this.flutterView);//1
this.launchView = this.createLaunchView();
if (this.launchView != null) {
this.addLaunchView();
}
}
1.通过setContentView 将Flutter视图放入window中
看下flutterView
public class FlutterView extends SurfaceView implements BinaryMessenger, TextureRegistry, AccessibilityStateChangeListener {
}
主要是做了native定位、生命周期、以及获取原生一些信息的通道。