【发布时间】:2020-12-17 04:22:13
【问题描述】:
我有独立的 Android 应用程序。然后我在Flutter 中开发了较小的网络应用程序并将其导出到网络服务器。它作为 Kotlin for Android 中独立应用程序的一部分加载到 WebView 中。
Android 支持 postmessaging,我可以通过渠道直接向WebView 发送数据。我的问题是如何在 Flutter Dart 代码中(在我的 Web 应用程序中)收听这些消息?
这是我在 Kotlin Android App 中使用的代码:
private var port: WebMessagePort? = null
@TargetApi(Build.VERSION_CODES.M)
private fun initPostMessagePort(){
val channelsAvailable = webView.createWebMessageChannel()
port = channelsAvailable.firstOrNull()
port?.apply {
setWebMessageCallback(object : WebMessageCallback() {
override fun onMessage(port: WebMessagePort, message: WebMessage) {
//TODO do something with message
}
})
}?:kotlin.run {
App.log("Port initialization failed - channels not available")
}
}
@TargetApi(Build.VERSION_CODES.M)
private fun sendMessageToPort(message: String){
port?.let { p->
webView.postWebMessage(WebMessage(message, arrayOf(p)), Uri.EMPTY)
}?:kotlin.run {
App.log("Port not initialized")
}
}
于是就有了我的 Flutter Web App 启动代码:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await di.init();
//listen to message from mobile app, then run code below
runApp(MyApp());
bloc.dispatch(GetUserProfile());
}
【问题讨论】:
标签: flutter flutter-web