index.uts 2.1 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4
import Context from "android.content.Context";
import BatteryManager from "android.os.BatteryManager";
import { UTSAndroid } from "io.dcloud.uts";

5
import { GetBatteryInfo, GetBatteryInfoSuccess, GetBatteryInfoResult,GetBatteryInfoSync } from '../interface.uts'
6 7 8 9
/**
 * 异步获取电量
 * @param {Object} options
 */
fxy060608's avatar
fxy060608 已提交
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
export const getBatteryInfo : GetBatteryInfo = function (options) {
    const context = UTSAndroid.getAppContext();
    if (context != null) {
        const manager = context.getSystemService(
            Context.BATTERY_SERVICE
        ) as BatteryManager;
        const level = manager.getIntProperty(
            BatteryManager.BATTERY_PROPERTY_CAPACITY
        );
        const res : GetBatteryInfoSuccess = {
            errMsg: 'getBatteryInfo:ok',
            level,
            isCharging: manager.isCharging()
        }
        options.success?.(res)
        options.complete?.(res)
    } else {
27 28 29 30 31 32 33
        // const res : GetBatteryInfoFail = {
        //     errSubject: "uni-getBatteryInfo",
        //     errCode: 1001,
        //     errMsg: 'getBatteryInfo:fail getAppContext is null',
        //     cause: null
        // }
		const res = new UniError("uni-getBatteryInfo", 1001, "getBatteryInfo:fail getAppContext is null")
fxy060608's avatar
fxy060608 已提交
34 35 36
        options.fail?.(res)
        options.complete?.(res)
    }
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
}

/**
 * 同步获取电量示例
 */
export const getBatteryInfoSync : GetBatteryInfoSync = function (): GetBatteryInfoResult {
	
    const context = UTSAndroid.getAppContext();
    if (context != null) {
        const manager = context.getSystemService(
            Context.BATTERY_SERVICE
        ) as BatteryManager;
        const level = manager.getIntProperty(
            BatteryManager.BATTERY_PROPERTY_CAPACITY
        );
		
		const res : GetBatteryInfoResult = {
		    level: level,
		    isCharging: manager.isCharging()
		};
		return res;
    } else {
		/**
		 * 无有效上下文
		 */
		const res : GetBatteryInfoResult = {
		    level: -1,
		    isCharging: false
		};
		return res;
    }
	
	
fxy060608's avatar
fxy060608 已提交
70
}