uni.getBatteryInfo(options)
获取电池电量信息
本 API 是 uni ext api,需下载插件:uni-getbatteryinfo
getBatteryInfo 兼容性
| Web | 微信小程序 | Android | Android uni-app x UTS 插件 | iOS | iOS uni-app x UTS 插件 | HarmonyOS |
| 4.0 | 4.35 | 3.9 | 3.9 | 4.11 | 4.11 | x |
参数
| 名称 | 类型 | 必填 | 默认值 | 兼容性 | 描述 |
| options | GetBatteryInfoOptions | 是 | - | |
Web
|
微信小程序
|
Android
|
iOS
|
HarmonyOS
| | - | - | - | - | x |
| |
| 名称 | 类型 | 必备 | 默认值 | 兼容性 | 描述 | | success | (res: GetBatteryInfoSuccess) => void | 否 | - | |
Web
|
微信小程序
|
Android
|
iOS
|
HarmonyOS
| | - | - | - | - | x |
| 接口调用成功的回调 | | fail | (res: UniError) => void | 否 | - | |
Web
|
微信小程序
|
Android
|
iOS
|
HarmonyOS
| | - | - | - | - | x |
| 接口调用失败的回调函数 | | complete | (res: any) => void | 否 | - | |
Web
|
微信小程序
|
Android
|
iOS
|
HarmonyOS
| | - | - | - | - | x |
| 接口调用结束的回调函数(调用成功、失败都会执行) |
|
GetBatteryInfoSuccess 的属性值
| 名称 | 类型 | 必备 | 默认值 | 兼容性 | 描述 |
| errMsg | string | 是 | - | |
Web
|
微信小程序
|
Android
|
iOS
|
HarmonyOS
| | - | - | - | - | x |
| |
| level | number | 是 | - | |
Web
|
微信小程序
|
Android
|
iOS
|
HarmonyOS
| | - | - | - | - | x |
| 设备电量,范围1 - 100 |
| isCharging | boolean | 是 | - | |
Web
|
微信小程序
|
Android
|
iOS
|
HarmonyOS
| | - | - | - | - | x |
| 是否正在充电中 |
示例
示例为hello uni-app x alpha分支,与最新HBuilderX Alpha版同步。与最新正式版同步的master分支示例另见
扫码体验 示例源码如下,请查看 pre > code 标签中的内容
<template>
<view>
<text>当前电量:{{level}}%</text>
<text>是否充电中:{{isCharging}}</text>
</view>
</template>
<script>
export default {
data() {
return {
level: 0,
isCharging: false
}
},
onLoad() {
try {
uni.getBatteryInfo({
success: res => {
this.level = res.level;
this.isCharging = res.isCharging;
}
});
} catch (e) {
console.error((e as Error).message);
uni.showModal({
content: (e as Error).message,
showCancel: false
});
}
}
}
</script>
参见
uni.getBatteryInfoSync()
同步获取电池电量信息
本 API 是 uni ext api,需下载插件:uni-getbatteryinfo
getBatteryInfoSync 兼容性
| Web | 微信小程序 | Android | Android uni-app x UTS 插件 | iOS | iOS uni-app x UTS 插件 | HarmonyOS |
| 4.0 | 4.35 | 3.9 | 3.9 | 4.11 | 4.11 | x |
返回值
| 类型 |
| GetBatteryInfoResult |
| 名称 | 类型 | 必备 | 默认值 | 兼容性 | 描述 | | level | number | 是 | - | |
Web
|
微信小程序
|
Android
|
iOS
|
HarmonyOS
| | - | - | - | - | x |
| 设备电量,范围1 - 100 | | isCharging | boolean | 是 | - | |
Web
|
微信小程序
|
Android
|
iOS
|
HarmonyOS
| | - | - | - | - | x |
| 是否正在充电中 |
|
参见
通用类型
GeneralCallbackResult
| 名称 | 类型 | 必备 | 默认值 | 兼容性 | 描述 |
| errMsg | string | 是 | - | |
Web
|
微信小程序
|
Android
|
iOS
|
HarmonyOS
| | - | 4.41 | - | - | - |
| 错误信息 |