android - FlutterActivity MethodChannel和FlutterView,腾讯大牛教你自己写Android第三方库
在Android平台上,Flutter提供了一个名为FlutterActivity
的类,用于嵌入Flutter在现有的Android应用中。如果你想要与Flutter交互,可以使用MethodChannel
来进行方法调用。
以下是一个简单的例子,展示如何在Android中创建一个MethodChannel
,并在Flutter端调用Android的方法:
- 在Android的
FlutterActivity
中注册MethodChannel
并设置一个处理方法。
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "samples.flutter.dev/battery";
@Override
public void configureFlutterEngine(FlutterEngine flutterEngine) {
MethodChannel methodChannel = new MethodChannel(flutterEngine.getDartExecutor(), CHANNEL);
methodChannel.setMethodCallHandler(
(call, result) -> {
// 处理来自Flutter的方法调用
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; // 示例返回100%
}
}
- 在Flutter端,通过
MethodChannel
调用Android的getBatteryLevel
方法。
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) {
评论已关闭