index.uts 1.5 KB
Newer Older
杜庆泉's avatar
杜庆泉 已提交
1 2 3
import Context from "android.content.Context";
import BatteryManager from "android.os.BatteryManager";

lizhongyi_'s avatar
lizhongyi_ 已提交
4
import { UTSAndroid } from "io.dcloud.uts";
杜庆泉's avatar
杜庆泉 已提交
5 6
import IntentFilter from 'android.content.IntentFilter';
import Intent from 'android.content.Intent';
杜庆泉's avatar
杜庆泉 已提交
7

lizhongyi_'s avatar
lizhongyi_ 已提交
8 9

export type GetBatteryInfoOptions = {
杜庆泉's avatar
杜庆泉 已提交
10 11 12
    success?: (res: object) => void
    fail?: (res: object) => void
    complete?: (res: object) => void
杜庆泉's avatar
杜庆泉 已提交
13 14
}

lizhongyi_'s avatar
lizhongyi_ 已提交
15 16

export function getBatteryInfo(options: GetBatteryInfoOptions) {
17
    const context = UTSAndroid.getAppContext();
杜庆泉's avatar
杜庆泉 已提交
18 19 20 21 22 23 24
    if (context != null) {
        const manager = context.getSystemService(
            Context.BATTERY_SERVICE
        ) as BatteryManager;
        const level = manager.getIntProperty(
            BatteryManager.BATTERY_PROPERTY_CAPACITY
        );
杜庆泉's avatar
杜庆泉 已提交
25 26 27 28 29 30 31
		
		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;
		
		
杜庆泉's avatar
杜庆泉 已提交
32
        const res = {
33 34 35
            errCode: 0,
            errSubject: "uni-getBatteryInfo",
            errMsg: "getBatteryInfo:ok",
杜庆泉's avatar
杜庆泉 已提交
36
            level,
杜庆泉's avatar
杜庆泉 已提交
37
            isCharging: isCharging
杜庆泉's avatar
杜庆泉 已提交
38
        }
39 40
        options.success?.(res)
        options.complete?.(res)
杜庆泉's avatar
杜庆泉 已提交
41 42
    } else {
        const res = {
43 44
			errCode: 1001,
			errSubject: "uni-getBatteryInfo",
杜庆泉's avatar
杜庆泉 已提交
45 46
            errMsg: 'getBatteryInfo:fail getAppContext is null'
        }
47 48
        options.fail?.(res)
        options.complete?.(res)
杜庆泉's avatar
杜庆泉 已提交
49
    }
50
}