
flutter/kotlin/Android 项目
官方代码: https://github.com/flutter/flutter/tree/master/examples/flutter_view
flutter入门(推荐):
https://github.com/alibaba/flutter-common-widgets-app

重点
MainAcvity
- 进入Android MainActivity 修改继承,
MainActivity() : Activity(), - manifest文件中,需改mainActiity主题
android:theme="@style/Theme.AppCompat"
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="@style/Theme.AppCompat"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- This keeps the window background of the activity showing
until Flutter renders its first frame. It can be removed if
there is no splash screen (such as the default splash screen
defined in @style/LaunchTheme). -->
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
FlutterMain.ensureInitializationComplet初始化flutterMain,保证flutterView可用,在setContentView配置layout之前
- 绑定flutter运行路径,以及入口
var flutterRunArguments = FlutterRunArguments()
//绑定路径
flutterRunArguments.bundlePath = FlutterMain.findAppBundlePath(applicationContext)
//获取入口 main方法
flutterRunArguments.entrypoint = "main"
- 设置消息频道,注意,第二个参数是频道,一定不能错。可用理解Android中广播,错误将无法接收传递
android_channel
messageChannel = BasicMessageChannel(flutterView, "android_channel", StringCodec.INSTANCE)
- 发送消息,这里为flutter接受的数据,传递
messageChannel?.send("from android message")
- 接收处理传递过来的消息
messageChannel?.setMessageHandler(object : BasicMessageChannel.MessageHandler<String> {
override fun onMessage(p0: String?, p1: BasicMessageChannel.Reply<String>?) {
print("BasicMessageChannel")
//处理来自 flutter main里面的消息
onFlutterMessage();
p1?.reply(EMPTY_MESSAGE);
}
})
flutter main中
- 设置频道,于上面的android_channel对应
static const BasicMessageChannel<String> platform =
BasicMessageChannel<String>("android_channel", StringCodec());
- 接收消息
//接收到Android activity发送到消息 处理消息
@override
void initState() {
super.initState();
platform.setMessageHandler(_handlePlatformMessage); //获取到消息处理方法
}
Future<String> _handlePlatformMessage(String message

本文介绍了如何在Flutter应用中与原生Android Activity进行交互,包括在MainActivity中修改继承、设置Flutter运行路径和入口、建立消息通道以及数据传递的详细步骤。同时提供了官方示例代码链接和关键代码片段。
最低0.47元/天 解锁文章
3362

被折叠的 条评论
为什么被折叠?



