Flutter与Android的混合跳转和通信
import android.content.Intent
import io.flutter.embedding.android.FlutterActivity
import io.flutter.plugin.common.MethodChannel
class MainActivity: FlutterActivity() {
private val CHANNEL = "samples.flutter.dev/battery"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->
if (call.method == "getBatteryLevel") {
val batteryLevel: Int = getBatteryLevel()
if (batteryLevel != -1) {
result.success(batteryLevel)
} else {
result.error("UNAVAILABLE", "Battery level not available", null)
}
} else {
result.notImplemented()
}
}
}
private fun getBatteryLevel(): Int {
val batteryLevel: Int = Intent(Intent.ACTION_BATTERY_SAVER_SETTINGS).let { intent ->
return@let registerForActivityResult(StartActivityForResult()) {
if (it.resultCode == Activity.RESULT_OK) {
// 处理正常跳转后的逻辑
}
}.launch(intent)
}
return batteryLevel
}
}
这个代码示例展示了如何在Flutter与Android混合开发的项目中,通过MethodChannel来实现Flutter页面向Android页面发起的请求,并处理回调。其中getBatteryLevel
方法展示了启动一个系统设置的例子,并处理了回调。这是一个很好的学习资源,对于了解混合架构下的页面跳转和通信非常有帮助。
评论已关闭