Flutter混合开发:Android与Flutter之间通信详细指南
在Android与Flutter之间进行通信时,可以使用MethodChannel
来实现。以下是一个简单的例子:
Android端(Kotlin):
import io.flutter.embedding.android.FlutterView
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
class MainActivity: AppCompatActivity() {
private val CHANNEL = "samples.flutter.dev/battery"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GeneratedPluginRegistrant.registerWith(this)
val flutterView = findViewById<FlutterView>(R.id.flutter_view)
MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->
if (call.method == "getBatteryLevel") {
val batteryLevel = getBatteryLevel()
if (batteryLevel != -1) {
result.success(batteryLevel)
} else {
result.error("UNAVAILABLE", "Battery level not available", null)
}
} else {
result.notImplemented()
}
}
}
private fun getBatteryLevel(): Int {
// 实现获取电池电量的逻辑
return 100 // 示例返回值
}
}
Flutter端(Dart):
import 'package:flutter/services.dart';
class BatteryLevel {
static const MethodChannel _channel =
const MethodChannel('samples.flutter.dev/battery');
static Future<int> get batteryLevel async {
final int batteryLevel = await _channel.invokeMethod('getBatteryLevel');
return batteryLevel;
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Battery Level')),
body: Center(
child: FutureBuilder<int>(
future: BatteryLevel.batteryLevel,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
return Text('Battery level at ${snapshot.data}%.');
} else {
return Text('Unable to get battery le
评论已关闭