index.uts 1.0 KB
Newer Older
杜庆泉's avatar
杜庆泉 已提交
1 2
import Context from "android.content.Context";
import BatteryManager from "android.os.BatteryManager";
3
import { UTSAndroid } from "io.dcloud.uts";
杜庆泉's avatar
杜庆泉 已提交
4 5 6


type GetBatteryInfoOptions = {
杜庆泉's avatar
杜庆泉 已提交
7 8 9
    success?: (res: object) => void
    fail?: (res: object) => void
    complete?: (res: object) => void
杜庆泉's avatar
杜庆泉 已提交
10 11
}

12
export default function getBatteryInfo(options: GetBatteryInfoOptions) {
13
    const context = UTSAndroid.getAppContext();
杜庆泉's avatar
杜庆泉 已提交
14 15 16 17 18 19 20 21 22 23 24 25
    if (context != null) {
        const manager = context.getSystemService(
            Context.BATTERY_SERVICE
        ) as BatteryManager;
        const level = manager.getIntProperty(
            BatteryManager.BATTERY_PROPERTY_CAPACITY
        );
        const res = {
            errMsg: 'getBatteryInfo:ok',
            level,
            isCharging: manager.isCharging()
        }
26 27
        options.success?.(res)
        options.complete?.(res)
杜庆泉's avatar
杜庆泉 已提交
28 29 30 31
    } else {
        const res = {
            errMsg: 'getBatteryInfo:fail getAppContext is null'
        }
32 33
        options.fail?.(res)
        options.complete?.(res)
杜庆泉's avatar
杜庆泉 已提交
34
    }
35
}