前言:
不赘述android studio,flutter和安卓环境搭建。不熟悉的自行百度
1.使用android studio创建flutter的plugin
file->new->new flutter project->选择flutter点击next
之后选择plugin,点create
2.插件目录
android,example,iOS,lib
首先运行一下exmple,然后使用studio打开exmple中的android项目,在安卓项目的TestPlugin类中加入获取电量的方法
// 获取电量
"getPlatformBattery" -> {
context?.let { result.success(getBatteryPercentage(it)) }
}
fun getBatteryPercentage(context: Context): Int {
return if (Build.VERSION.SDK_INT >= 21) {
val bm = context.getSystemService(BATTERY_SERVICE) as BatteryManager
bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
} else {
val iFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
val batteryStatus: Intent? = context.registerReceiver(null, iFilter)
val level =
batteryStatus?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1
val scale =
batteryStatus?.getIntExtra(BatteryManager.EXTRA_SCALE, -1) ?: -1
val batteryPct = level / scale.toDouble()
(batteryPct * 100).toInt()
}
}
注意:可以看到需要context参数
4.实现ActivityAware接口
class TestFlutterPlugin : FlutterPlugin, MethodCallHandler, ActivityAware{
private var context: Context? = null
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
context = binding.activity
}
override fun onDetachedFromActivityForConfigChanges() {
context = null
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
context = binding.activity
}
override fun onDetachedFromActivity() {
context = null
}
}
5.example中调用
String _platformBattery= 'Unknown';
@override
void initState() {
super.initState();
initPlatformState();
initBattery();
}
Future<void> initBattery() async {
String platformBattery;
try {
platformBattery = await TestFlutterPlugin.platformBattery?? 'Unknown platform version';
} on Exception {
platformBattery = 'Failed to get platform version.';
}
if (!mounted) return;
setState(() {
_platformBattery = platformBattery;
});
}
完事,关于上传pub可以百度,私人插件本地引用看example