index.uts 2.4 KB
Newer Older
1 2 3
import Context from "android.content.Context";
import BatteryManager from "android.os.BatteryManager";

4 5 6 7 8
import { GetBatteryInfo, GetBatteryInfoOptions, GetBatteryInfoSuccess, GetBatteryInfoResult, GetBatteryInfoSync } from '../interface.uts'
import IntentFilter from 'android.content.IntentFilter';
import Intent from 'android.content.Intent';

import { GetBatteryInfoFailImpl } from '../unierror';
DCloud-yyl's avatar
DCloud-yyl 已提交
9

10 11 12
/**
 * 异步获取电量
 */
13 14 15 16 17 18 19 20 21 22 23 24 25 26
export const getBatteryInfo : GetBatteryInfo = function (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
    );

    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
杜庆泉 已提交
27

28 29 30 31
    const res : GetBatteryInfoSuccess = {
      errMsg: 'getBatteryInfo:ok',
      level,
      isCharging: isCharging
32
    }
33 34 35 36 37 38 39
    options.success?.(res)
    options.complete?.(res)
  } else {
    let res = new GetBatteryInfoFailImpl(1001);
    options.fail?.(res)
    options.complete?.(res)
  }
40 41 42
}

/**
43
 * 同步获取电量
44
 */
45 46 47 48 49 50 51 52 53
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
    );
杜庆泉's avatar
杜庆泉 已提交
54

55 56 57 58
    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
杜庆泉 已提交
59

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
    const res : GetBatteryInfoResult = {
      level: level,
      isCharging: isCharging
    };
    return res;
  }
  else {
    /**
     * 无有效上下文
     */
    const res : GetBatteryInfoResult = {
      level: -1,
      isCharging: false
    };
    return res;
  }
杜庆泉's avatar
杜庆泉 已提交
76
}