index.uts 1.1 KB
Newer Older
DCloud-yyl's avatar
DCloud-yyl 已提交
1 2
import Context from "android.content.Context";
import BatteryManager from "android.os.BatteryManager";
3
import { UTSAndroid } from "io.dcloud.uts";
DCloud-yyl's avatar
DCloud-yyl 已提交
4 5 6 7 8 9 10 11 12


type GetBatteryInfoOptions = {
    success?: (res: UTSJSONObject) => void
    fail?: (res: UTSJSONObject) => void
    complete?: (res: UTSJSONObject) => void
}

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