例子为获取并显示 Android 手机电量,要在工程中生成 Android,iOS 文件,需要使用如下命令创建工程:
flutter create -i objc -a java myapp
生成的工程目录如下:
Windows os 上安装的 flutter 版本:
flutter --version
Flutter 3.0.5
在 Android 机上显示手机电量:
1. main.dart
:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Native Code'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _batteryLevel = -999;
Future<void> _getBatteryLevel() async {
// ourse.flutter.dev/battery is a random identifier
const platform = MethodChannel('course.flutter.dev/battery');
try {
final batteryLevel = await platform.invokeMethod('getBatteryLevel');
setState(() {
_batteryLevel = batteryLevel;
});
} on PlatformException catch (error) {
setState(() {
_batteryLevel = -9999;
});
}
}
void initState() {
// TODO: implement initState
super.initState();
_getBatteryLevel();
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Text('Battery Level: ${_batteryLevel.toString()}'),
),
);
}
}
2. 修改 MainActivity.java
代码
此文件为 java 文件,所在位置:
代码:
package com.example.myapp;
import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
public class MainActivity extends FlutterActivity {
public void configureFlutterEngine( FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), "course.flutter.dev/battery")
.setMethodCallHandler(new MethodCallHandler() {
public void onMethodCall(MethodCall call, Result result) {
if (call.method.equals("getBatteryLevel")) {
int batteryLevel = getBatteryLevel();
if (batteryLevel != -1) {
result.success(batteryLevel);
} else {
result.error("UNAVAILABLE", "Could not fetch battery level.", null);
}
} else {
result.notImplemented();
}
}
});
}
private int getBatteryLevel() {
int batteryLevel = -1;
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
} else {
Intent intent = new ContextWrapper(getApplicationContext()).registerReceiver(null,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
batteryLevel = (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100)
/ intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
}
return batteryLevel;
}
}
运行界面如下,电量 100%。
虽然这样写代码是可行的, 但在实际中,要运行 Android 代码,并不一定需要自己这样写 java 代码,通常使用现有的插件等等。