一、背景
为了更好地支持将Flutter添加到现有项目的执行环境,旧的Android平台端包装器在 io.flutter.app.FlutterActivity
及其相关类托管Flutter运行时已被弃用。取而代之的则是 io.flutter.embedding.android.FlutterActivity
及其相关的类。如果我们不进行升级,那么运行flutter doctor命令时会报如下的错误。
Your Flutter application is created using an older version of the Android
embedding. It is being deprecated in favor of Android embedding v2. Follow the
steps athttps://flutter.dev/go/android-project-migrationto migrate your project. You may also pass the --ignore-deprecation flag to
ignore this check and continue with the deprecated v1 embedding. However,
the v1 Android embedding will be removed in future versions of Flutter.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The detected reason was:No `/Users/mac/android/AndroidManifest.xml` file
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
如果是纯Flutter工程,只需要打开 \android\app\src\main
目录下的AndroidManifest.xml文件,然后添加如下的代码即可解决。
<manifest><application><meta-data android:name="flutterEmbedding" android:value="2" /></application>
</manifest>
二、迁移
如果是原生混合开发的项目,则可以参考下面的步骤进行:
- 首先,打开FlutterActivity主页面,重新导入
import io.flutter.embedding.android.FlutterActivity
。
- 如果你在MainActivity.java中有自定义平台通道代码,那么你需要做如下的更新:
换句话说,就是将 onCreate
中代码的通道注册部分移到 onfigureFlutterEngine
方法中,并使用 flutterEngine.getDartExecutor(). getbinarymessenger()
作为二进制信使,而不是 getFlutterView()
。
- 接下来,打开
android/app/src/main/AndroidManifest.xml
,全局替换FlutterApplication
为${applicationName}
,如下。
<applicationandroid:name="io.flutter.app.FlutterApplication"><!-- code omitted -->
</application>
<applicationandroid:name="${applicationName}"><!-- code omitted -->
</application>
- 更新启动画面,移除所有带有android键的标签
:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
,然后在styles.xml中添加一个启动主题,将所需的启动屏幕配置为Drawable的背景。
<!-- You can name this style whatever you'd like -->
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar"><item name="android:windowBackground">@drawable/[your_launch_drawable_here]</item>
</style>
接着,配置MainActivity以启动主题,然后切换到正常的主题,直到Flutter呈现其第一帧:
<activity android:name=".MainActivity"android:theme="@style/LaunchTheme"// some code omitted><!-- Specify that the launch screen should continue being displayed --><!-- until Flutter renders its first frame. --><meta-dataandroid:name="io.flutter.embedding.android.SplashScreenDrawable"android:resource="@drawable/launch_background" /><!-- Theme to apply as soon as Flutter begins rendering frames --><meta-dataandroid:name="io.flutter.embedding.android.NormalTheme"android:resource="@style/NormalTheme"/><!-- some code omitted -->
</activity>
- 在
<application>
中添加一个新的标记。
<meta-dataandroid:name="flutterEmbedding"android:value="2" />