flutter和Android原生交互的三种方式
在Flutter中,与Android原生代码交互主要有三种方式:MethodChannel、EventChannel和BasicMessageChannel。
- MethodChannel:用于传递方法调用(方法和回调)。
在Flutter端:
const platform = MethodChannel('samples.flutter.dev/battery');
String _getBatteryLevel() {
String batteryLevel;
try {
final int result = await platform.invokeMethod('getBatteryLevel');
batteryLevel = 'Battery level at $result% .';
} on PlatformException catch (e) {
batteryLevel = "Failed to get battery level: '${e.message}'.";
}
return batteryLevel;
}
在Android端:
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import android.os.Bundle;
public class MainActivity extends FlutterActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
new MethodChannel(getFlutterView(), "samples.flutter.dev/battery").setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
if (call.method.equals("getBatteryLevel")) {
int batteryLevel = getBatteryLevel();
if (batteryLevel != -1) {
result.success(batteryLevel);
} else {
result.error("UNAVAILABLE", "Battery level not available", null);
}
} else {
result.notImplemented();
}
}
}
);
}
private int getBatteryLevel() {
// ...获取电池电量的逻辑
return 100; // 假设的返回值
}
}
- EventChannel:用于数据流的通信。
在Flutter端:
const EventChannel battery = EventChannel('samples.flutter.dev/batteryStatus');
Stream<String> get batteryState {
return battery.receiveBroadcastStream().map((buffer) => _parseEvent(buffer));
}
String _parseEvent(dynamic event) {
// 解析事件的逻辑
return "Event: $event";
}
在Android端:
import io.flutter.plugin.common.EventChannel;
import io.flutter.view.FlutterView;
import android.os.Bundle;
public class MainActivity extends FlutterActivity {
@Ov
评论已关闭