Flutter
自從1.0版本發佈,如今愈來愈受歡迎,不少公司都在研究或者用在項目上。今天實踐一下Android
原生項目如何嵌套Flutter
頁面,具體原理就是Flutter
做爲Android Module
出如今項目中,這樣就能夠在已有的項目中使用,Android
項目也是一個工程,Flutter
項目也是一個工程,這樣就互不相關,也很好進行管理。廢話很少說,開始實踐。html
首先講一下整個工程的結構:java
在建立Android工程前,新建一個文件夾(目錄),取名叫:mixProject,裏面在建立兩個文件夾分別是:flutter和native,示意圖以下:注意:後面flutter文件夾會刪除,這裏這是說明整個工程的目錄android
下面就在native文件夾建立Android工程,File
->
New
->
New Project
:
建立工程以前先把flutte
文件夾目錄刪除,在mixProject
目錄下以Module形式建立Flutter工程,File
->New
->New Flutter Project
,這裏要注意,選類型的要選Flutter Module
,Flutter項目跟Android工程根文件夾是同級的,它不一樣於普通的Android module存在於Android工程根目錄下。c++
這樣Android工程和Flutter工程都已經建立好了。 另外也能夠經過(在項目根目錄下)命令flutter create -t module my_flutter去建立Flutter的Module
工程。git
下面在Android工程下添加對Flutter工程的依賴,在項目根目錄下setting.gradle
添加以下:github
//insert
setBinding(new Binding([gradle: this])) // new
evaluate(new File( // new
settingsDir.parentFile, // new
'my_flutter/.android/include_flutter.groovy' // new
))
複製代碼
這樣要注意:
xxxx/.android/include_flutter.groovy
中的xxxx必定要和以module形式建立的Flutter工程名一致。 這時候
Sync
一下,發現Flutter的module已經添加到項目中了。
在Android工程app
下的build.gradle
下對Flutter的依賴:json
//加入Flutter的依賴
implementation project(':flutter') 複製代碼
這時候在同步一下,若是沒報錯,證實flutter工程已經依賴進Android工程裏了,若是出現下面錯誤:segmentfault
flutter工程和Android工程下minSdkVersion要一致。在Android
原生調用Flutter
頁面以前,先知道FlutterActivity
這個類,在建立的FlutterModule
中.android
->app
->flutter_module
->host
下有個MainActivity
,這個類是繼承FlutterActivity
類,在AndroidManifest.xml
下而且配置了這個啓動界面,也就是說當原生Android
調用Flutter
時,該類是Flutter
項目的頁面入口。那麼下面看看這個類的源碼,到底作了什麼?api
Activity
,也就是它仍是普通的
Activity
,另外還實現了三個接口:
這個接口只有一個方法:數組
public interface Provider {
FlutterView getFlutterView();
}
複製代碼
只是返回當前Activity
中的FlutterView
。
public interface PluginRegistry {
//註冊插件
PluginRegistry.Registrar registrarFor(String var1);
//是否有這個插件
boolean hasPlugin(String var1);
//插件發佈值
<T> T valuePublishedByPlugin(String var1);
//爲插件註冊生命回調
public interface PluginRegistrantCallback {
void registerWith(PluginRegistry var1);
}
//視圖銷燬監聽
public interface ViewDestroyListener {
boolean onViewDestroy(FlutterNativeView var1);
}
//用戶手動離開當前activity監聽,如主動切換任何,按back健
//系統自動切換應用不會調用此方法,如來電,滅屏
public interface UserLeaveHintListener {
void onUserLeaveHint();
}
//監聽Activity是否執行onNewIntent的回調
public interface NewIntentListener {
boolean onNewIntent(Intent var1);
}
//監聽Activity是否執行onActivityResult
public interface ActivityResultListener {
boolean onActivityResult(int var1, int var2, Intent var3);
}
//監聽Activity是否請求權限的回調
public interface RequestPermissionsResultListener {
boolean onRequestPermissionsResult(int var1, String[] var2, int[] var3);
}
//插件的註冊者
public interface Registrar {
//插件宿主的activity
Activity activity();
//插件的上下文 Application Context
Context context();
//這是當前Activity的context
Context activeContext();
//信使 主要用來註冊Platform channels
BinaryMessenger messenger();
//返回TextureRegistry 能夠拿到SurfaceTexture
TextureRegistry textures();
//返回PlatformViewRegistry
PlatformViewRegistry platformViewRegistry();
//返回FlutterView
FlutterView view();
//根據key來尋找資源
String lookupKeyForAsset(String var1);
//同理根據key來尋找資源
String lookupKeyForAsset(String var1, String var2);
//發佈值
PluginRegistry.Registrar publish(Object var1);
//增長回調
PluginRegistry.Registrar addRequestPermissionsResultListener(PluginRegistry.RequestPermissionsResultListener var1);
//增長回調
PluginRegistry.Registrar addActivityResultListener(PluginRegistry.ActivityResultListener var1);
//增長回調newIntent回調
PluginRegistry.Registrar addNewIntentListener(PluginRegistry.NewIntentListener var1);
//增長回調
PluginRegistry.Registrar addUserLeaveHintListener(PluginRegistry.UserLeaveHintListener var1);
//增長回調視圖銷燬
PluginRegistry.Registrar addViewDestroyListener(PluginRegistry.ViewDestroyListener var1);
}
}
複製代碼
//視圖工廠
public interface ViewFactory {
//建立FlutterView
FlutterView createFlutterView(Context var1);
//建立FlutterNativeView
FlutterNativeView createFlutterNativeView();
//是否保留FlutterNativeView
boolean retainFlutterNativeView();
}
複製代碼
也就是FlutterActivity
實現上面三個接口主要是建立視圖,返回視圖以及監聽生命週期的回調。下面回到FlutterActivity
,FLutterActivityDelegate
後面再分析:
//建立委託類FlutterActivityDelegate對象
private final FlutterActivityDelegate delegate = new FlutterActivityDelegate(this, this);
private final FlutterActivityEvents eventDelegate;
private final Provider viewProvider;
private final PluginRegistry pluginRegistry;
//構造函數
public FlutterActivity() {
//FlutterActivityDelegate實現了FlutterActivityEvents,Provider,PluginRegistry 賦值對應的變量,調用更加清晰
this.eventDelegate = this.delegate;
this.viewProvider = this.delegate;
this.pluginRegistry = this.delegate;
}
複製代碼
而且Activity
的生命週期函數都是由FlutterActivityEvents
對象來執行:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.eventDelegate.onCreate(savedInstanceState);
}
protected void onStart() {
super.onStart();
this.eventDelegate.onStart();
}
protected void onResume() {
super.onResume();
this.eventDelegate.onResume();
}
protected void onDestroy() {
this.eventDelegate.onDestroy();
super.onDestroy();
}
public void onBackPressed() {
if (!this.eventDelegate.onBackPressed()) {
super.onBackPressed();
}
}
protected void onStop() {
this.eventDelegate.onStop();
super.onStop();
}
protected void onPause() {
super.onPause();
this.eventDelegate.onPause();
}
protected void onPostResume() {
super.onPostResume();
this.eventDelegate.onPostResume();
}
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
this.eventDelegate.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (!this.eventDelegate.onActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
protected void onNewIntent(Intent intent) {
this.eventDelegate.onNewIntent(intent);
}
public void onUserLeaveHint() {
this.eventDelegate.onUserLeaveHint();
}
public void onTrimMemory(int level) {
this.eventDelegate.onTrimMemory(level);
}
public void onLowMemory() {
this.eventDelegate.onLowMemory();
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
this.eventDelegate.onConfigurationChanged(newConfig);
}
複製代碼
下面看看建立FlutterView
以及返回FlutterView
的方法:
public FlutterView getFlutterView() {
//經過FlutterActivityDelegate委託執行
return this.viewProvider.getFlutterView();
}
//子類實現 返回null
public FlutterView createFlutterView(Context context) {
return null;
}
//子類實現 返回null
public FlutterNativeView createFlutterNativeView() {
return null;
}
複製代碼
插件管理的方法實現:
public final boolean hasPlugin(String key) {
//也是經過FlutterActivityDelegate委託執行
return this.pluginRegistry.hasPlugin(key);
}
public final <T> T valuePublishedByPlugin(String pluginKey) {
return this.pluginRegistry.valuePublishedByPlugin(pluginKey);
}
public final Registrar registrarFor(String pluginKey) {
return this.pluginRegistry.registrarFor(pluginKey);
}
複製代碼
那麼這裏很清晰地知道FlutterActivity
的生命週期各個方法實際由FlutterActivityDelegate
代理執行,而且知道FlutterActivity
經過委託代理的方式解決來生命週期的回調,插件管理和FlutterView
的建立,是Android
原生調Flutter
頁面的中間橋樑。
通過上面的分析,FlutterActivityDelegate
做爲委託的角色存在,下面更進一步地去深刻:
public FlutterActivityDelegate(Activity activity, FlutterActivityDelegate.ViewFactory viewFactory) {
this.activity = (Activity)Preconditions.checkNotNull(activity);
this.viewFactory = (FlutterActivityDelegate.ViewFactory)Preconditions.checkNotNull(viewFactory);
}
複製代碼
FlutterActivityDelegate
構造函數須要傳入Activity
對象和FlutterActivityDelegate.ViewFactory
,其實重點看Activity
對象就行,由於傳遞給委託類FlutterActivityDelegate
的ViewFactory
並無生成FlutterView
,剛好相反,FlutterView
是經過傳遞進來的Activity
來生成的。在FlutterActivityDelegate
類源碼能夠看到,定義類和Activity
同名的函數,如:onCreate,onPause,onStart,onResume。在FlutterActivity
中調用這個委託類同名函數,所以得出Flutter
頁面是由該委託類處理的。下面具體看一下onCreate
方法:
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初始化完成
FlutterMain.ensureInitializationComplete(this.activity.getApplicationContext(), args);
//注意這裏,在FlutterActivity默認返回null的
this.flutterView = this.viewFactory.createFlutterView(this.activity);
//因此會走到這裏
if (this.flutterView == null) {
//這裏也是建立類空FlutterNativeView
FlutterNativeView nativeView = this.viewFactory.createFlutterNativeView();
//這裏纔是實際建立了FlutterView
this.flutterView = new FlutterView(this.activity, (AttributeSet)null, nativeView);
//設置佈局參數,添加到當前activity,做爲主視圖
this.flutterView.setLayoutParams(matchParent);
this.activity.setContentView(this.flutterView);
//建立啓動ui
this.launchView = this.createLaunchView();
if (this.launchView != null) {
this.addLaunchView();
}
}
//根據activity獲取intent中傳遞的路由值
if (!this.loadIntent(this.activity.getIntent())) {
//獲取路由值 去跳轉flutter項目設定的route對應頁面
//查找bundle
String appBundlePath = FlutterMain.findAppBundlePath(this.activity.getApplicationContext());
if (appBundlePath != null) {
this.runBundle(appBundlePath);
}
}
}
複製代碼
上面的步驟就是:
FlutterActivityDelegate
這個類的onCreate
方法主要是建立FlutterView
而且設置到Activity
上,而後經過loadIntent
方法去讀取intent
中傳遞的路由值去跳轉到Flutter
項目中對應的頁面去。上面講述道Activity
會將FlutterView
設置到setContView
裏,下面簡單看看FlutterView
源碼:
public class FlutterView extends SurfaceView implements BinaryMessenger, TextureRegistry 複製代碼
看到FlutterView
繼承了SurfaceView
,至於爲何要繼承SurfaceView
,由於SurfaceView
使用的繪圖線程不是UI線程,平時須要圖形性能比較高的場景就得須要它了。
public class FlutterView extends SurfaceView implements BinaryMessenger, TextureRegistry {
private final NavigationChannel navigationChannel;//重點看這個
private final KeyEventChannel keyEventChannel;
private final LifecycleChannel lifecycleChannel;
private final LocalizationChannel localizationChannel;
//構造函數
public FlutterView(Context context) {
this(context, (AttributeSet)null);
}
public FlutterView(Context context, AttributeSet attrs) {
this(context, attrs, (FlutterNativeView)null);
}
public FlutterView(Context context, AttributeSet attrs, FlutterNativeView nativeView) {
super(context, attrs);
this.nextTextureId = new AtomicLong(0L);
this.mIsSoftwareRenderingEnabled = false;
this.onAccessibilityChangeListener = new OnAccessibilityChangeListener() {
public void onAccessibilityChanged(boolean isAccessibilityEnabled, boolean isTouchExplorationEnabled) {
FlutterView.this.resetWillNotDraw(isAccessibilityEnabled, isTouchExplorationEnabled);
}
};
Activity activity = getActivity(this.getContext());
if (activity == null) {
throw new IllegalArgumentException("Bad context");
} else {
//若是傳遞的FlutterNativeView是空
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();
//適配窗口變化,並在合適的時候更新mMetrics,設置到native中
this.mMetrics = new FlutterView.ViewportMetrics();
this.mMetrics.devicePixelRatio = context.getResources().getDisplayMetrics().density;
}
}
}
複製代碼
下面重點觀察NavigationChannel
這個導航Channel:
public class NavigationChannel {
@NonNull
public final MethodChannel channel;
public NavigationChannel(@NonNull DartExecutor dartExecutor) {
//建立MethodChannel
this.channel = new MethodChannel(dartExecutor, "flutter/navigation", JSONMethodCodec.INSTANCE);
}
//設置初始路由
public void setInitialRoute(String initialRoute) {
this.channel.invokeMethod("setInitialRoute", initialRoute);
}
//將指定路由壓入棧
public void pushRoute(String route) {
this.channel.invokeMethod("pushRoute", route);
}
//將指定路由彈出棧
public void popRoute() {
this.channel.invokeMethod("popRoute", (Object)null);
}
//設置MethodCallHandler
public void setMethodCallHandler(@Nullable MethodCallHandler handler) {
this.channel.setMethodCallHandler(handler);
}
}
複製代碼
也就是說FlutterView
導航是經過MethodChannel
與Flutter
進行通訊,最終交由Flutter
處理。作個插件都知道,在Flutter
確定存在MethodChannel('flutter/navigation',JSONMethodCodec)
,在ststem_channels.dart
中找到:
/// A JSON [MethodChannel] for navigation.
///
/// The following incoming methods are defined for this channel (registered
/// using [MethodChannel.setMethodCallHandler]):
///
/// * `popRoute`, which is called when the system wants the current route to
/// be removed (e.g. if the user hits a system-level back button).
///
/// * `pushRoute`, which is called with a single string argument when the
/// operating system instructs the application to open a particular page.
///
/// See also:
///
/// * [WidgetsBindingObserver.didPopRoute] and
/// [WidgetsBindingObserver.didPushRoute], which expose this channel's
/// methods.
static const MethodChannel navigation = MethodChannel(
'flutter/navigation',
JSONMethodCodec(),
);
複製代碼
而且在widgets/binding.dart
找到對應實現:
Future<dynamic> _handleNavigationInvocation(MethodCall methodCall) {
switch (methodCall.method) {
case 'popRoute':
//壓入棧
return handlePopRoute();
case 'pushRoute':
//出棧
return handlePushRoute(methodCall.arguments);
}
return Future<dynamic>.value();
}
複製代碼
可是沒有看到setInitialRoute
處理,那麼在哪裏會用到呢?在app.dart
下:
/// The [MaterialApp] configures the top-level [Navigator] to search for routes
/// in the following order:
///
/// 1. For the `/` route, the [home] property, if non-null, is used.
///
/// 2. Otherwise, the [routes] table is used, if it has an entry for the route.
///
/// 3. Otherwise, [onGenerateRoute] is called, if provided. It should return a
/// non-null value for any _valid_ route not handled by [home] and [routes].
///
/// 4. Finally if all else fails [onUnknownRoute] is called.
///
/// If a [Navigator] is created, at least one of these options must handle the
/// `/` route, since it is used when an invalid [initialRoute] is specified on
/// startup (e.g. by another application launching this one with an intent on
/// Android; see [Window.defaultRouteName]).
///
/// This widget also configures the observer of the top-level [Navigator] (if
/// any) to perform [Hero] animations.
///
/// If [home], [routes], [onGenerateRoute], and [onUnknownRoute] are all null,
/// and [builder] is not null, then no [Navigator] is created.
/// {@macro flutter.widgets.widgetsApp.initialRoute}
final String initialRoute;
複製代碼
上面說明了Natvigator
配置尋找路由順序:
widgetsApp
下具體說明:/// {@template flutter.widgets.widgetsApp.initialRoute}
/// The name of the first route to show, if a [Navigator] is built.
///
/// Defaults to [Window.defaultRouteName], which may be overridden by the code
/// that launched the application.
///
/// If the route contains slashes, then it is treated as a "deep link", and
/// before this route is pushed, the routes leading to this one are pushed
/// also. For example, if the route was `/a/b/c`, then the app would start
/// with the three routes `/a`, `/a/b`, and `/a/b/c` loaded, in that order.
///
/// If any part of this process fails to generate routes, then the
/// [initialRoute] is ignored and [Navigator.defaultRouteName] is used instead
/// (`/`). This can happen if the app is started with an intent that specifies
/// a non-existent route.
/// The [Navigator] is only built if routes are provided (either via [home],
/// [routes], [onGenerateRoute], or [onUnknownRoute]); if they are not,
/// [initialRoute] must be null and [builder] must not be null.
///
/// See also:
///
/// * [Navigator.initialRoute], which is used to implement this property.
/// * [Navigator.push], for pushing additional routes.
/// * [Navigator.pop], for removing a route from the stack.
/// {@endtemplate}
final String initialRoute;
複製代碼
若是生成了[navigator],則initialRoute是第一個展現的默認路由,默認是Window.defaultRouteName,而在window.dart對defaultName更進一步的說明:
/// The route or path that the embedder requested when the application was
/// launched.
///
/// This will be the string "`/`" if no particular route was requested.
///
/// ## Android
///
/// On Android, calling
/// [`FlutterView.setInitialRoute`](/javadoc/io/flutter/view/FlutterView.html#setInitialRoute-java.lang.String-)
/// will set this value. The value must be set sufficiently early, i.e. before
/// the [runApp] call is executed in Dart, for this to have any effect on the
/// framework. The `createFlutterView` method in your `FlutterActivity`
/// subclass is a suitable time to set the value. The application's
/// `AndroidManifest.xml` file must also be updated to have a suitable
/// [`<intent-filter>`](https://developer.android.com/guide/topics/manifest/intent-filter-element.html).
///
/// ## iOS
///
/// On iOS, calling
/// [`FlutterViewController.setInitialRoute`](/objcdoc/Classes/FlutterViewController.html#/c:objc%28cs%29FlutterViewController%28im%29setInitialRoute:)
/// will set this value. The value must be set sufficiently early, i.e. before
/// the [runApp] call is executed in Dart, for this to have any effect on the
/// framework. The `application:didFinishLaunchingWithOptions:` method is a
/// suitable time to set this value.
///
/// See also:
///
/// * [Navigator], a widget that handles routing.
/// * [SystemChannels.navigation], which handles subsequent navigation
/// requests from the embedder.
String get defaultRouteName => _defaultRouteName();
String _defaultRouteName() native 'Window_defaultRouteName';
複製代碼
註釋的意思若是沒有特定的路由,默認是**/和Android和IOS**如何設置該值方式和時機,再回到FlutterView
裏:
public void setInitialRoute(String route) {
this.navigationChannel.setInitialRoute(route);
}
複製代碼
到這裏,已經清楚Flutter
如何接受native
傳遞的路由參數過程了。就是經過FlutterView
能夠設置該路由值,在native
建立FlutterView
而且經過setInitialRoute
方法設置route
(window.defaultRouteName),而Flutter
經過window.defaultRouteName
從而知道native
要跳轉到Flutter
項目的哪一個頁面。 再回到FlutterView
的構造函數中,或者你們和我可能會有疑惑:爲何要建立FlutterNativeView
呢?那下面簡單看看FlutterNativeView
的源碼:
public class FlutterNativeView implements BinaryMessenger {
private static final String TAG = "FlutterNativeView";
//插件管理
private final FlutterPluginRegistry mPluginRegistry;
private final DartExecutor dartExecutor;
private FlutterView mFlutterView;
private final FlutterJNI mFlutterJNI;
private final Context mContext;
private boolean applicationIsRunning;
public FlutterNativeView(@NonNull Context context) {
this(context, false);
}
public FlutterNativeView(@NonNull Context context, boolean isBackgroundView) {
this.mContext = context;
this.mPluginRegistry = new FlutterPluginRegistry(this, context);
//建立FlutterJNI
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();
}
}
複製代碼
能夠看到FlutterNativeView
實現了BinaryMessenger
接口,根據其意思能夠得知,這個BinaryMessenger是一個數據信息交流對象,接口聲明以下:
public interface BinaryMessenger {
void send(String var1, ByteBuffer var2);
void send(String var1, ByteBuffer var2, BinaryMessenger.BinaryReply var3);
void setMessageHandler(String var1, BinaryMessenger.BinaryMessageHandler var2);
public interface BinaryReply {
void reply(ByteBuffer var1);
}
public interface BinaryMessageHandler {
void onMessage(ByteBuffer var1, BinaryMessenger.BinaryReply var2);
}
}
複製代碼
這是用於Flutter
和Native
之間交換數據的接口類,已知FlutterView
已經實現了SurfaceView
,而FlutterNativeView
負責FlutterView
和Flutter
之間的通信,再使用Skia
繪製頁面。
下面再看看FlutterJNI
這個類:
public class FlutterJNI {
...
public FlutterJNI() {
}
private native void nativeDestroy(long var1);
private native long nativeAttach(FlutterJNI var1, boolean var2);
private static native void nativeDetach(long var0);
private static native void nativeRunBundleAndSnapshot(long var0, String var2, String var3, String var4, boolean var5, AssetManager var6);
private static native void nativeRunBundleAndSource(long var0, String var2, String var3, String var4);
private static native void nativeSetAssetBundlePathOnUI(long var0, String var2);
private static native String nativeGetObservatoryUri();
private static native void nativeDispatchEmptyPlatformMessage(long var0, String var2, int var3);
private static native void nativeDispatchPlatformMessage(long var0, String var2, ByteBuffer var3, int var4, int var5);
}
複製代碼
發現涉及到不少和native打交道的方法,能夠知道NativeView
顯然是一個插件、消息的管理類,並與native打交道,那麼和FlutterView
的關係,顯然一個負責展現,一個負責交互。
在上面分析FlutterActivity
實現了getFlutterView
方法,也分析到在FlutterActivityDelegate建立了FlutterView
並添加到當前Activity
中。當FlutterView
被添加到Activity
,那麼Flutter
怎麼知道native
打開哪一個頁面呢,實際上是經過loadIntent
這個方法來打開對應的頁面,下面具體看看這個再FlutterActivityDelegate
這個類裏的loadIntent
方法:
//根據activity獲取intent中傳遞的路由值
if (!this.loadIntent(this.activity.getIntent())) {
String appBundlePath = FlutterMain.findAppBundlePath(this.activity.getApplicationContext());
if (appBundlePath != null) {
this.runBundle(appBundlePath);
}
}
.....
private boolean loadIntent(Intent intent) {
String action = intent.getAction();
if ("android.intent.action.RUN".equals(action)) {
String route = intent.getStringExtra("route");
String appBundlePath = intent.getDataString();
if (appBundlePath == null) {
//查找bundle
appBundlePath = FlutterMain.findAppBundlePath(this.activity.getApplicationContext());
}
if (route != null) {
//flutterView初始化,參數爲路由
this.flutterView.setInitialRoute(route);
}
this.runBundle(appBundlePath);
return true;
} else {
return false;
}
}
複製代碼
//runBundle方法
private void runBundle(String appBundlePath) {
//第一次啓動flutter頁面isApplicationRunning()爲false
if (!this.flutterView.getFlutterNativeView().isApplicationRunning()) {
FlutterRunArguments args = new FlutterRunArguments();
ArrayList<String> bundlePaths = new ArrayList();
//檢查是否有flutter相關資源,這裏用於動態更新
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]);
args.entrypoint = "main";
//經過flutterView.runFromBundle()來執行
this.flutterView.runFromBundle(args);
}
}
複製代碼
能夠看到最後經過FlutterView
的runFromBundle()
執行。
public void runFromBundle(FlutterRunArguments args) {
this.assertAttached();
this.preRun();
this.mNativeView.runFromBundle(args);
this.postRun();
}
複製代碼
調用FlutterNativeView
的runFromBundle
方法:
public void runFromBundle(FlutterRunArguments args) {
boolean hasBundlePaths = args.bundlePaths != null && args.bundlePaths.length != 0;
if (args.bundlePath == null && !hasBundlePaths) {
throw new AssertionError("Either bundlePath or bundlePaths must be specified");
} else if ((args.bundlePath != null || args.defaultPath != null) && hasBundlePaths) {
throw new AssertionError("Can't specify both bundlePath and bundlePaths");
} else if (args.entrypoint == null) {
throw new AssertionError("An entrypoint must be specified");
} else {
if (hasBundlePaths) {
this.runFromBundleInternal(args.bundlePaths, args.entrypoint, args.libraryPath);
} else {
this.runFromBundleInternal(new String[]{args.bundlePath, args.defaultPath}, args.entrypoint, args.libraryPath);
}
}
}
複製代碼
當Bundle參數不爲空的時候,調用runFromBundleInternal
方法:
private void runFromBundleInternal(String[] bundlePaths, String entrypoint, String libraryPath) {
this.assertAttached();
if (this.applicationIsRunning) {
throw new AssertionError("This Flutter engine instance is already running an application");
} else {
this.mFlutterJNI.runBundleAndSnapshotFromLibrary(bundlePaths, entrypoint, libraryPath, this.mContext.getResources().getAssets());
this.applicationIsRunning = true;
}
}
複製代碼
最後經過FlutterJNI
來調用JNI
方法執行:
@UiThread
public void runBundleAndSnapshotFromLibrary(@NonNull String[] prioritizedBundlePaths, @Nullable String entrypointFunctionName, @Nullable String pathToEntrypointFunction, @NonNull AssetManager assetManager) {
this.ensureAttachedToNative();
this.nativeRunBundleAndSnapshotFromLibrary(this.nativePlatformViewId, prioritizedBundlePaths, entrypointFunctionName, pathToEntrypointFunction, assetManager);
}
複製代碼
/data/data/包名/flutter/flutter_assets/
的路徑值,這就是路由值。最後調用c++方法將main
函數調起,以後就執行widget
綁定,UI渲染等。這裏發現nativeRunBundleAndSnapshotFromLibrary
須要傳四個參數。
這裏能夠得出,只要打開FlutterActivity
頁面的時候,經過intent
傳入的key,若是這個值於Flutter
項目定義的route值同樣,就能跳到對應的頁面。下面用一張圖簡單描述流程:
Activity
,只不過這個
Activity
鋪了
FlutterView
來顯示,那下面具體實踐。
這邊例子只有主頁面(Activity),主頁面由一個ViewPager
和底部RadioGroup
組成:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@+id/view_line"/>
<View
android:id="@+id/view_line"
android:layout_width="match_parent"
android:layout_height="2dp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toTopOf="@+id/rl_bottom_radio"
android:background="#ece7e7"/>
<RelativeLayout
android:id="@+id/rl_bottom_radio"
android:layout_width="match_parent"
android:layout_height="60dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
>
<RadioGroup
android:id="@+id/rg_foot_bar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<RadioButton
android:id="@+id/radio_button_one"
style="@style/main_footer_bar_radio"
android:checked="true"
android:drawableTop="@drawable/widget_bar_one"
android:text="跳轉到flutter"
/>
<RadioButton
android:="@+id/radio_button_two"
style="@style/main_footer_bar_radio"
android:drawableTop="@drawable/widget_bar_two"
android:text="測試"
/>
<RadioButton
android:="@+id/radio_button_three"
style="@style/main_footer_bar_radio"
android:drawableTop="@drawable/widget_bar_three"
android:text="網絡"
/>
</RadioGroup>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
複製代碼
ViewPager
分別由三個Fragment
組成,分別是跳到Flutter
頁面,測試頁面和網絡加載Flutter
頁面。 MainActivity
:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
<View
android:id="@+id/view_line"
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#ece7e7" />
<RelativeLayout
android:id="@+id/rl_bottom_radio"
android:layout_width="match_parent"
android:layout_height="60dp"
>
<RadioGroup
android:id="@+id/rg_foot_bar"
android:layout_width="match_parent"
android:layout_height="60dp"
android:orientation="horizontal">
<RadioButton
android:id="@+id/radio_button_one"
style="@style/main_footer_bar_radio"
android:checked="true"
android:drawableTop="@drawable/widget_bar_one"
android:text="跳轉到flutter" />
<RadioButton
android:id="@+id/radio_button_two"
style="@style/main_footer_bar_radio"
android:drawableTop="@drawable/widget_bar_two"
android:text="第二個頁面" />
<RadioButton
android:id="@+id/radio_button_three"
style="@style/main_footer_bar_radio"
android:drawableTop="@drawable/widget_bar_three"
android:text="嵌套flutter頁面" />
</RadioGroup>
</RelativeLayout>
</LinearLayout>
複製代碼
在io.flutter.facade下自動生成了FlutterFragment
/** * A {@link Fragment} managing a {@link FlutterView}. * * <p><strong>Warning:</strong> This file is auto-generated by Flutter tooling. * DO NOT EDIT.</p> */
public class FlutterFragment extends Fragment {
public static final String ARG_ROUTE = "route";
private String mRoute = "/";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mRoute = getArguments().getString(ARG_ROUTE);
}
}
@Override
public void onInflate(Context context, AttributeSet attrs, Bundle savedInstanceState) {
super.onInflate(context, attrs, savedInstanceState);
}
@Override
public FlutterView onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return Flutter.createView(getActivity(), getLifecycle(), mRoute);
}
}
複製代碼
繼續點擊Flutter.createView
方法:
/** * 建立一個連接(FlutterVIew)將指定Activity和生命週期連接起來 * 可選初始路由字符串用於肯定顯示哪一個小部件,默認的初始路由是「/」 * * Creates a {@link FlutterView} linked to the specified {@link Activity} and {@link Lifecycle}. * The optional initial route string will be made available to the Dart code (via * {@code window.defaultRouteName}) and may be used to determine which widget should be displayed * in the view. The default initialRoute is "/". * * @param activity an {@link Activity} * @param lifecycle a {@link Lifecycle} * @param initialRoute an initial route {@link String}, or null * @return a {@link FlutterView} */
@NonNull
public static FlutterView createView(@NonNull final Activity activity, @NonNull final Lifecycle lifecycle, final String initialRoute) {
FlutterMain.startInitialization(activity.getApplicationContext());
FlutterMain.ensureInitializationComplete(activity.getApplicationContext(), null);
final FlutterNativeView nativeView = new FlutterNativeView(activity);
final FlutterView flutterView = new FlutterView(activity, null, nativeView) {
private final BasicMessageChannel<String> lifecycleMessages = new BasicMessageChannel<>(this, "flutter/lifecycle", StringCodec.INSTANCE);
@Override
public void onFirstFrame() {
super.onFirstFrame();
setAlpha(1.0f);
}
@Override
public void onPostResume() {
// Overriding default behavior to avoid dictating system UI via PlatformPlugin.
lifecycleMessages.send("AppLifecycleState.resumed");
}
};
if (initialRoute != null) {
flutterView.setInitialRoute(initialRoute);
}
lifecycle.addObserver(new LifecycleObserver() {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate() {
final FlutterRunArguments arguments = new FlutterRunArguments();
arguments.bundlePath = FlutterMain.findAppBundlePath(activity.getApplicationContext());
arguments.entrypoint = "main";
flutterView.runFromBundle(arguments);
GeneratedPluginRegistrant.registerWith(flutterView.getPluginRegistry());
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart() {
flutterView.onStart();
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {
flutterView.onPostResume();
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause() {
flutterView.onPause();
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop() {
flutterView.onStop();
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
flutterView.destroy();
}
});
flutterView.setAlpha(0.0f);
return flutterView;
}
複製代碼
看到這個Flutter.createView(getActivity),getLifecycle(),mRoute
這行代碼已經幫咱們初始了FlutterMain
,FlutterNativeView
,FlutterView
,而且返回FlutterView
,那如今能夠思考,那是否是建立這個系統生成的fragment就能嵌套Flutter
頁面了?實踐一下:
private void initListener(){
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
//這裏的邏輯是若是點擊
@Override
public void onPageSelected(int position) {
//若是點擊第三個RadioButton
if(position == 2){
//若是沒有初始化就初始化FlutterFragment
if(isFirstInitFlutterView){
initFlutterFragment();
isFirstInitFlutterView = false;
}
}
}
@Override
public void onPageScrollStateChanged(int i) {
}
});
}
/** * * 初始化FlutterFragment * */
private void initFlutterFragment(){
mFragmentAdapter.updateFragment(2,new FlutterFragment());
//更新Fragment
mFragmentAdapter.notifyDataSetChanged();
}
複製代碼
看看效果圖:
能夠看到只經過new FlutterFragment
代碼便可把
Flutter
頁面嵌套到原生Android裏。
能夠發現上面跳到Flutter
項目的主頁面(默認頁面),下面經過指定的參數跳到指定頁面
爲了方便,下面本身實現FlutterFragment
:
public class MyFlutterFragment extends Fragment {
private static final String TAG = "MyFlutterFragment";
//路由
public static final String AGR_ROUTE = "_route_";
//參數
public static final String PARAMS = "_params_";
private String mRoute = "/";
private String mParams = "";
private FlutterView mFlutterView;
public static MyFlutterFragment newInstance(String route,String params){
Bundle args = new Bundle();
MyFlutterFragment fragment = new MyFlutterFragment();
args.putString(MyFlutterFragment.AGR_ROUTE,route);
args.putString(MyFlutterFragment.PARAMS,params);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if(getArguments() != null){
mRoute = getArguments().getString(AGR_ROUTE);
mParams = getArguments().getString(PARAMS);
//這裏拼接參數
JSONObject jsonObject = new JSONObject();
JSONObject pageParamsObject;
if(!TextUtils.isEmpty(mParams)){
try {
//json字符串
pageParamsObject = new JSONObject(mParams);
jsonObject.put("pageParams",pageParamsObject);
mRoute = mRoute + "?" + jsonObject.toString();
Log.d("ssd",mRoute);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState){
Log.d(TAG,"onCreateView-mRoute:"+mRoute);
mFlutterView = Flutter.createView(getActivity(),getLifecycle(),mRoute);
//綜合解決閃屏,佈局覆蓋問題
mFlutterView.setZOrderOnTop(true);
mFlutterView.setZOrderMediaOverlay(false);
mFlutterView.getHolder().setFormat(Color.parseColor("#00000000"));
//註冊channel
// GeneratedPluginRegistrant.registerWith(mFlutterView.getPluginRegistry());
//返回FlutterView
return mFlutterView;
}
}
複製代碼
先把main.dart
文件代碼全部代碼刪除,我這裏把它做爲參數解析和路由跳轉:
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:io';
import 'dart:ui';
import 'package:flutter/services.dart';
import 'package:flutter_module/ui/tab_fragment.dart';
void main(){
//接受路由參數 路由參數能夠自定義規則
//window.defaultRouteName 就是獲取native傳遞的路由參數
runApp(_widgetForRoute(window.defaultRouteName));
//runApp(_widgetForRoute("tab_fragment"));
//
// if(Platform.isAndroid){
// //Android同步沉浸式
// SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(statusBarColor: Colors.transparent);
// SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
//
// }
}
/** * 路由參數處理 * */
Widget _widgetForRoute(String route){
print("route:" + route.toString());
//解析路由參數
String pageName = _getPageName(route);
Map<String,dynamic> pageParams = json.decode(_parseNativeParams(route));
//路由參數
print("pageName:" + pageName.toString());
//業務參數
print("pageParams:" + pageParams.toString());
//截取跳轉到哪一個頁面參數
switch(pageName){
case 'tab_fragment':
return new TabFragment();
}
}
/** * 解析路由參數 * */
String _getPageName(String route){
String pageName = route;
if (route.indexOf("?") != -1)
//截取?以前的字符串 代表後面帶有業務參數
pageName = route.substring(0,route.indexOf("?"));
print("pageName:" + pageName);
return pageName;
}
/** * 返回業務參數 * */
String _parseNativeParams(String route){
Map<String,dynamic> nativeParams = {};
if(route.indexOf("?") != -1){
nativeParams = json.decode(route.substring(route.indexOf("?") + 1));
}
return nativeParams['pageParams'] ?? "{}";
}
複製代碼
main.dart
主要是解析路由參數和業務,傳參的規則是能夠自定義的,我這邊傳參是路由+業務參數,由上面看到Flutter
經過window.defaultRouteName
獲得Android
原生所傳遞的參數。上面經過_widgetForRoute
方法來跳轉原生傳遞給Flutter
的參數對應頁面,上面例子原生傳遞了tab_fragment
,在_widgetForRoute
會進入**case 'tab_fragment'**條件裏,最後跳到tab_fragment
中:
tab_fragment
主要是用dio
網絡庫來作一個請求網絡功能
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:flutter_module/util/http_util.dart';
/** * 原生Fragment嵌套Flutter * */
class TabFragment extends StatefulWidget {
String content = "Tab3";
@override
_TabFragmentState createState() => _TabFragmentState();
}
class _TabFragmentState extends State<TabFragment>{
String text = "這是默認內容";
@override
void initState(){
super.initState();
}
@override
Widget build(BuildContext context){
return MaterialApp(
home: new Scaffold(
body: new Container(
color: Colors.greenAccent,
child:new ListView(
children: <Widget>[
new Padding(padding:EdgeInsets.only(top:200)),
new Container(
alignment: Alignment.center,
child: new Text(
widget.content,
style: new TextStyle(
color:Colors.white,
fontSize: 40,
fontWeight: FontWeight.normal,
decoration: TextDecoration.none
),
),
),
new Padding(padding: EdgeInsets.only(top:200)),
new Container(
width: 100,
alignment: Alignment.center,
child:new MaterialButton(
child:new Text("網絡1請求測試"),
color: Colors.greenAccent,
onPressed: (){
//網絡請求模擬
buttonClick();
},
)
),
new Container(
alignment: Alignment.center,
child: new Text(
text,
style: new TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.normal,
decoration: TextDecoration.none
),
),
),
],
),
),
),
);
}
/** * 點擊網絡請求 * */
void buttonClick() async {
Response response = await HttpUtil().doGet("api/test");
if(response != null){
if(response.statusCode == 200){
setState(() {
print("請求成功-response:"+response.data.toString());
text = response.data.toString();
});
} else {
print("請求失敗,請檢查網絡後重試");
}
} else {
print("請求失敗,請檢查網絡後重試");
}
}
}
複製代碼
最後調用:
/** * * 初始化FlutterFragment * */
private void initFlutterFragment(){
mFragmentAdapter.updateFragment(2,MyFlutterFragment.newInstance("tab_fragment","ssssss"));
//更新Fragment
mFragmentAdapter.notifyDataSetChanged();
}
複製代碼
效果圖以下:
點擊 嵌套Flutter頁面,返現Flutter頁面
以
Fragment
形式嵌套在原生中了。
上面分析過,能夠經過FlutterActivity
來直接跳到Flutter
頁面,並從FlutterActivityDelegate
源碼咱們可按照如下幾個步驟來實現:
/** * * Android ->Flutter(FlutterActivity爲載體) */
public class FlutterMainActivity extends FlutterActivity implements MethodChannel.MethodCallHandler{
private static final String TAG = "FlutterMainActivity";
private String routeStr = "";
private static final String TOAST_CHANNEL = "com.test.native_flutter/toast";
@Override
protected void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
//執行FlutterMain初始化
FlutterMain.startInitialization(getApplicationContext());
//插件註冊
GeneratedPluginRegistrant.registerWith(this);
registerCustomPlugin(this);
}
private void registerCustomPlugin(PluginRegistry register){
registerMethodChannel();
}
private void registerMethodChannel(){
//調用原生toast
new MethodChannel(this.registrarFor(TOAST_CHANNEL).messenger(),TOAST_CHANNEL);
}
@Override
public FlutterView createFlutterView(Context context){
getIntentData();
WindowManager.LayoutParams matchParent = new WindowManager.LayoutParams(-1, -1);
//建立FlutterNativeView
FlutterNativeView nativeView = this.createFlutterNativeView();
//建立FlutterView
FlutterView flutterView = new FlutterView(FlutterMainActivity.this,(AttributeSet)null,nativeView);
//給FlutterView傳遞路由參數
flutterView.setInitialRoute(routeStr);
//FlutterView設置佈局參數
flutterView.setLayoutParams(matchParent);
//將FlutterView設置進ContentView中,設置內容視圖
this.setContentView(flutterView);
return flutterView;
}
/** * 獲取參數信息 * 傳遞給flutterVIew */
private void getIntentData(){
String route = getIntent().getStringExtra("_route_");
String params = getIntent().getStringExtra("_params_");
JSONObject jsonObject = new JSONObject();
try{
jsonObject.put("pageParams",params);
} catch (JSONException e){
e.printStackTrace();
}
//字符串是路由參數 + 業務參數
//形式以下:test?{"pageParams":"{\"content\":\"這是測試內容\"}"}
routeStr = route + "?" + jsonObject.toString();
Log.d(TAG,"onCreate-route:" + route + "-params" + params);
Log.d(TAG,"pnCreate-routeStr:" + routeStr);
}
/** * 插件要實現的方法 * @param methodCall * @param result */
@Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
switch(methodCall.method){
case "showToast"://調用原生的toast
String content = methodCall.argument("content");
Toast.makeText(this, content, Toast.LENGTH_SHORT).show();
break;
default:
result.notImplemented();
}
}
}
複製代碼
在第一個fragment
增長跳轉到這Activity
代碼:
private void initListener(){
btnNativeToFlutter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//跳轉到FlutterMainActivity
Map<String,Object> map = new HashMap<>();
//而且攜帶業務參數
map.put("content","這是測試內容");
String jsonString = new Gson().toJson(map);
String route = "test";
Intent intent = new Intent(getActivity(), FlutterMainActivity.class);
intent.putExtra("_route_",route);
intent.putExtra("_params_",jsonString);
startActivity(intent);
}
});
}
複製代碼
注意傳遞給FlutterMainActivity
的路由參數是test,那麼須要在Flutter
增長test
頁面:
class Test extends StatefulWidget{
final String content;//wowId
Test({this.content});
_TestState createState() => _TestState();
}
class _TestState extends State<Test>{
@override
void initState(){
super.initState();
print('content:' + widget.content);
}
@override
Widget build(BuildContext context){
return MaterialApp(
home:new Scaffold(
appBar: new AppBar(
brightness: Brightness.light,
title: new Text(
'Flutter',
style: new TextStyle(fontSize: 20,color:Color(0xFF1A1A1A)),
),
centerTitle: true,
elevation: 0,
backgroundColor: Colors.blue,
leading: new IconButton(
icon:new Icon(Icons.arrow_back),
color:Color(0xFF333333),
onPressed: (){
closeFlutter(context);
},
),
),
body: new Container(
color: Colors.white,
child: new ListView(
children: <Widget>[
new Padding(padding: EdgeInsets.only(top:100)),
new Container(
alignment: Alignment.center,
child: new Text(
widget.content,
style: new TextStyle(
color: Colors.red,
fontSize: 40,
fontWeight: FontWeight.normal,
decoration: TextDecoration.none
),
),
),
new Container(
width: 100,
alignment: Alignment.center,
child: new MaterialButton(
child: new Text("打開原生的toast"),
color: Colors.greenAccent,
onPressed: (){
buttonClick();
}),
),
],
),
),
),
);
}
//彈出toast
void buttonClick(){
ToastUtil.showToastInfo("哈哈哈");
}
//返回頁面
void closeFlutter(BuildContext context){
NavigatorUtil.close(context);
}
}
複製代碼
在Flutter
項目的main.dart
文件配置若是路由參數是test
的邏輯:
//截取跳轉到哪一個頁面參數
switch(pageName){
case 'tab_fragment':
return new TabFragment();
case 'test'://test頁面
//獲取業務參數
String content = pageParams["content"] ?? "defaultContent";
return new Test(content:content,);
}
複製代碼
debug環境下效果以下:
能夠看到debug
下會有明顯的黑屏現象,那麼
release
會不會是這樣呢?
release環境下效果以下:
能夠看到release
下原生跳轉到
Flutter
沒有了黑屏,且切換速度很快。
在第一種方式Fragment
能夠知道,Fragment
經過在onCreateView
方法裏建立FlutterView
並返回便可與Flutter
交互,那麼能不能在普通Activity
經過setContentView
方法把FlutterView
設置顯示視圖,最終達到交互目的呢?下面嘗試一下:
/** * Android -> Flutter (普通Activity) * */
public class MyFlutterActivity extends AppCompatActivity implements MethodChannel.MethodCallHandler {
private static final String TOAST_CHANNEL = "com.test.native_flutter/toast";
private FlutterView flutterView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceStae){
super.onCreate(savedInstanceStae);
String route = getIntent().getStringExtra("_route_");
String params = getIntent().getStringExtra("_params_");
JSONObject jsonObject = new JSONObject();
try{
jsonObject.put("pageParams",params);
} catch(JSONException e){
e.printStackTrace();
}
//建立FlutterView
flutterView = Flutter.createView(this,getLifecycle(),route + "?" + jsonObject.toString());
//設置顯示視圖
setContentView(flutterView);
//插件註冊
registerMethodChannel();
}
@Override
public void onBackPressed(){
if(flutterView != null){
flutterView.popRoute();
}else{
super.onBackPressed();
}
}
private void registerMethodChannel(){
new MethodChannel(flutterView,TOAST_CHANNEL).setMethodCallHandler(this);
}
@Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
switch(methodCall.method){
case "showToast":
//調用原生的Toast
String content = methodCall.argument("content");
Toast.makeText(this,content,Toast.LENGTH_SHORT).show();
break;
default:
result.notImplemented();
}
}
}
複製代碼
一樣也是能夠的。
Flutter
跳轉native
方式就很簡單了,和彈出吐司同樣,在onMethodCall
作跳轉就能夠了,例如:
// 自定義插件
String CHANNEL = "xxx.plugin";
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(new MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, Result result) {
if (call.method.equals("routeName")) {
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
MainActivity.this.startActivity(intent);
result.success("success");
} else {
result.notImplemented();
}
}
});
複製代碼
可見Google
團隊想的很全面。
經過native
和Flutter
兩個項目來達到混合開發的優點是互不影響,在native
不須要考慮Flutter
是否影響自己,並經過閱讀FlutterActivity
和FlutterView
部分源碼,能夠知道下面幾點:
FlutterView
是native
和Flutter
的橋樑。FlutterActivity
,經過Intent
傳入具體的路由值,再由FlutterView
經過setInitialRoute
方法設置Flutter
中的window.defaultRouteName
。FlutterActivityDelegate
,實現對FlutterActivity
和Flutter
頁面的聲明週期管理,FlutterView
是繼承SurfaceView
,而native
和Flutter
之間的通信是FlutterNativeView
。native
和Flutter
是兩個項目,是能夠分別單獨運行。Flutter筆記--Flutter頁面嵌入Android Activity中