docs/api/get-battery-info.md
获取电池电量信息
本 API 是 uni ext api,需下载插件:uni-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 | <a style="color:unset;" href="https://vote.dcloud.net.cn/#/?name=uni-app%20x">x</a> |
| 名称 | 类型 | 必填 | 默认值 | 兼容性 | 描述 |
|---|---|---|---|---|---|
| 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 | 接口调用结束的回调函数(调用成功、失败都会执行) |
| 名称 | 类型 | 必备 | 默认值 | 兼容性 | 描述 |
|---|---|---|---|---|---|
| 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分支示例另见 ::: preview https://hellouniappx.dcloud.net.cn/web/#/pages/API/get-battery-info/get-battery-info
appRedirect https://hellouniappx.dcloud.net.cn/appredirect.html?path=pages/API/get-battery-info/get-battery-info
示例
<template>
<view>
<text>当前电量:{{data.level}}%</text>
<text>是否充电中:{{data.isCharging}}</text>
</view>
</template>
<script setup lang="uts">
type DataType = {
level: number;
isCharging: boolean;
}
const data = reactive({
level: 0,
isCharging: false
} as DataType)
onLoad(() => {
try {
uni.getBatteryInfo({
success: res => {
data.level = res.level;
data.isCharging = res.isCharging;
}
});
} catch (e) {
console.error((e as Error).message);
uni.showModal({
content: (e as Error).message,
showCancel: false
});
}
})
defineExpose({
data
})
</script>
:::
同步获取电池电量信息
本 API 是 uni ext api,需下载插件:uni-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 | <a style="color:unset;" href="https://vote.dcloud.net.cn/#/?name=uni-app%20x">x</a> |
| 类型 |
|---|
| GetBatteryInfoResult |
| 名称 | 类型 | 必备 | 默认值 | 兼容性 | 描述 |
|---|---|---|---|---|---|
| level | number | 是 | - | Web: -; 微信小程序: -; Android: -; iOS: -; HarmonyOS: x | 设备电量,范围1 - 100 |
| isCharging | boolean | 是 | - | Web: -; 微信小程序: -; Android: -; iOS: -; HarmonyOS: x | 是否正在充电中 |
| 名称 | 类型 | 必备 | 默认值 | 兼容性 | 描述 |
|---|---|---|---|---|---|
| errMsg | string | 是 | - | Web: -; 微信小程序: 4.41; Android: -; iOS: -; HarmonyOS: - | 错误信息 |