Android与Flutter混合开发之flutter_boos
2020-05-04 本文已影响0人
Jade_4c8c
一、背景
近期在做Android项目转型为Flutter,在转型的过程中,我们选择的是各业务模块逐各替换的方式。这种方式下必然会涉及到Android与Flutter的交互,而阿里提供的flutter_boost就是交互之作。
二、demo介绍
github:https://github.com/zbyJade/AndroidWithFlutter.git
如果下载后请进行如下操作
如果还报错请重启
image.png
功能介绍:
- Android原生界面跳转Flutter界面,并传参
- Flutter界面跳转Android原生界面,并传参
-
Android和Flutter在同一界面显示
1.jpg
三、创建flutter_module
1.为了使demo代码简洁,新建一个Android工程,我用的是AS 3.6.3
image.pngimage.png
2.新建flutter module
image.pngimage.png
Project location 建议选择到你的Android project下,这样较清晰 image.png
image.png
3.添加配置(AS 3.6会自动生成)
Project Settings
evaluate(new File(
settingsDir,
'flutter_module/.android/include_flutter.groovy'
))
include ':flutter_module'
app build.grade
implementation project(path: ':flutter')
4.创建module后,产生的问题和解决办法(如果没有出现更好)
问题1:该Wring可忽略
image.png
问题2:
image.png
定位到问题文件,可删除框内文件
image.png
四、依赖flutter_boost
image.png如果你使用了Androidx找到兼容的版本
image.png
添加flutter_boost最新依赖
image.png
实现过程如下
flutter_boost: ^1.12.13+1
image.png
image.png
如果要是没有出现flutter和flutter_boost的module就稍微等一会
image.png
添加module
image.png
image.png
五、使用flutter_boost
5.1 封装PageRouter,界面跳转的路由工具类
public class PageRouter {
// 界面格式可自定义
public final static String OnePageUrl = "url://onePage";
public final static String NativePage = "url://nativePage";
public final static Map<String, String> pageName = new HashMap<String, String>() {{
put(OnePageUrl, "onePage");
}};
public static boolean openPageByUrl(Context context, String url, Map params) {
return openPageByUrl(context, url, params, 0);
}
public static boolean openPageByUrl(Context context, String url, Map params, int requestCode) {
String flutterPage = null;
if (url.startsWith(OnePageUrl)) {
flutterPage = pageName.get(OnePageUrl);
Intent intent = BoostFlutterActivity.withNewEngine().url(flutterPage).params(params)
.backgroundMode(BoostFlutterActivity.BackgroundMode.opaque).build(context);
context.startActivity(intent);
return true;
} else if (url.startsWith(NativePage)) {
String aNative = (String) params.get("native");
Bundle bundle = new Bundle();
bundle.putString("native", aNative);
context.startActivity(new Intent(context, NativePageActivity.class).putExtras(bundle));
return true;
}
return false;
}
}
5.2 Application中初始化(记着在AndroidManifest里引入BaseApplication)
public class BaseApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// 初始化
initFlutterBoost();
}
private void initFlutterBoost() {
Platform platform = new FlutterBoost.ConfigBuilder(this, new INativeRouter(){
@Override
public void openContainer(Context context, String url, Map<String, Object> urlParams, int requestCode, Map<String, Object> exts) {
String assembleUrl = Utils.assembleUrl(url, urlParams);
PageRouter.openPageByUrl(context, assembleUrl, urlParams);
}
}).isDebug(true)
.whenEngineStart(FlutterBoost.ConfigBuilder.ANY_ACTIVITY_CREATED)
.build();
FlutterBoost.instance().init(platform);
}
}
5.3 声明BoostFlutterActivity
<!-- 声明加载flutter界面的activity-->
<activity
android:name="com.idlefish.flutterboost.containers.BoostFlutterActivity"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
android:hardwareAccelerated="true"
android:theme="@style/Theme.AppCompat"
android:windowSoftInputMode="adjustResize">
<!--添加loading-->
<!--如果不添加meta-data会出现黑色闪屏-->
<!--如果只添加name,不添加resource会运行不起来-->
<!--resource需设置一个loading图片-->
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="@drawable/svg_loading_page" />
</activity>
5.4 activity跳转flutter界面,并传递参数
findViewById(R.id.bt1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 将map传递到flutter界面
HashMap<String, String> params = new HashMap<>();
params.put("OneKey","从Android跳转到Flutter界面");
PageRouter.openPageByUrl(MainActivity.this, PageRouter.OnePageUrl, params);
}
});
5.5 flutter界面跳转activity,并传递参数
children: <Widget>[
// 如果接收到参数则显示,OneKey为传递map中的key
Text(widget.param == null ? "未接收到参数" : widget.param["OneKey"]),
RaisedButton(
child: Text("调回Android界面"),
onPressed: () {
// url://nativePage为PageRouter界面定义的,flutter调起Android界面
FlutterBoost.singleton.open("url://nativePage",
urlParams: {"native": "我是参数乙"});
}),
RaisedButton(
child: Text("关闭当前界面"),
onPressed: () {
Navigator.of(context).pop();
}),
],
5.6 Android和flutter混合界面
public class NativeAndFlutterActivity extends AppCompatActivity implements SplashScreenProvider {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_native_and_flutter);
// 将flutter界面作为fragment添加到FrameLayout上
FlutterFragment mFragment = new FlutterFragment.NewEngineFragmentBuilder().url("fragmentPage").build();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_stub, mFragment)
.commit();
}
@Override
public SplashScreen provideSplashScreen() {
// 为显示加载loading
Drawable manifestSplashDrawable = getSplashScreenFromManifest();
if (manifestSplashDrawable != null) {
return new DrawableSplashScreen(manifestSplashDrawable, ImageView.ScaleType.CENTER, 500L);
} else {
return null;
}
}
protected static final String SPLASH_SCREEN_META_DATA_KEY = "io.flutter.embedding.android.SplashScreenDrawable";
private Drawable getSplashScreenFromManifest() {
try {
@SuppressLint("WrongConstant") ActivityInfo activityInfo = getPackageManager().getActivityInfo(
getComponentName(),
PackageManager.GET_META_DATA | PackageManager.GET_ACTIVITIES
);
Bundle metadata = activityInfo.metaData;
Integer splashScreenId = metadata != null ? metadata.getInt(SPLASH_SCREEN_META_DATA_KEY) : null;
return splashScreenId != null
? Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP
? getResources().getDrawable(splashScreenId, getTheme())
: getResources().getDrawable(splashScreenId)
: null;
} catch (PackageManager.NameNotFoundException e) {
// This is never expected to happen.
return null;
}
}
}
结尾
本篇文章仅介绍了flutter_boost的基础使用。更加详细的demo 代码请到github上下载。希望对读者flutter学习过程有所帮助。