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