index.uts 1.5 KB
Newer Older
lizhongyi_'s avatar
lizhongyi_ 已提交
1 2 3
import Context from "android.content.Context";
import BatteryManager from "android.os.BatteryManager";
import { UTSAndroid } from "io.dcloud.uts";
杜庆泉's avatar
杜庆泉 已提交
4 5
import IntentFilter from 'android.content.IntentFilter';
import Intent from 'android.content.Intent';
lizhongyi_'s avatar
lizhongyi_ 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23


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


export function getBatteryInfo(options: GetBatteryInfoOptions) {
    const context = UTSAndroid.getAppContext();
    if (context != null) {
        const manager = context.getSystemService(
            Context.BATTERY_SERVICE
        ) as BatteryManager;
        const level = manager.getIntProperty(
            BatteryManager.BATTERY_PROPERTY_CAPACITY
        );
杜庆泉's avatar
杜庆泉 已提交
24 25 26 27 28 29 30
		
		let ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
		let batteryStatus = context.registerReceiver(null, ifilter);
		let status = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
		let isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
		
		
lizhongyi_'s avatar
lizhongyi_ 已提交
31 32 33 34 35
        const res = {
            errCode: 0,
            errSubject: "uni-getBatteryInfo",
            errMsg: "getBatteryInfo:ok",
            level,
杜庆泉's avatar
杜庆泉 已提交
36
            isCharging: isCharging
lizhongyi_'s avatar
lizhongyi_ 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49
        }
        options.success?.(res)
        options.complete?.(res)
    } else {
        const res = {
			errCode: 1001,
			errSubject: "uni-getBatteryInfo",
            errMsg: 'getBatteryInfo:fail getAppContext is null'
        }
        options.fail?.(res)
        options.complete?.(res)
    }
}