index.uts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import Context from "android.content.Context";
  2. import BatteryManager from "android.os.BatteryManager";
  3. import { GetBatteryInfo, GetBatteryInfoOptions, GetBatteryInfoSuccess, GetBatteryInfoResult, GetBatteryInfoSync } from '../interface.uts'
  4. import IntentFilter from 'android.content.IntentFilter';
  5. import Intent from 'android.content.Intent';
  6. import { GetBatteryInfoFailImpl } from '../unierror';
  7. /**
  8. * 异步获取电量
  9. */
  10. export const getBatteryInfo : GetBatteryInfo = function (options : GetBatteryInfoOptions) {
  11. const context = UTSAndroid.getAppContext();
  12. if (context != null) {
  13. const manager = context.getSystemService(
  14. Context.BATTERY_SERVICE
  15. ) as BatteryManager;
  16. const level = manager.getIntProperty(
  17. BatteryManager.BATTERY_PROPERTY_CAPACITY
  18. );
  19. let ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
  20. let batteryStatus = context.registerReceiver(null, ifilter);
  21. let status = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
  22. let isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
  23. const res : GetBatteryInfoSuccess = {
  24. errMsg: 'getBatteryInfo:ok',
  25. level,
  26. isCharging: isCharging
  27. }
  28. options.success?.(res)
  29. options.complete?.(res)
  30. } else {
  31. let res = new GetBatteryInfoFailImpl(1001);
  32. options.fail?.(res)
  33. options.complete?.(res)
  34. }
  35. }
  36. /**
  37. * 同步获取电量
  38. */
  39. export const getBatteryInfoSync : GetBatteryInfoSync = function () : GetBatteryInfoResult {
  40. const context = UTSAndroid.getAppContext();
  41. if (context != null) {
  42. const manager = context.getSystemService(
  43. Context.BATTERY_SERVICE
  44. ) as BatteryManager;
  45. const level = manager.getIntProperty(
  46. BatteryManager.BATTERY_PROPERTY_CAPACITY
  47. );
  48. let ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
  49. let batteryStatus = context.registerReceiver(null, ifilter);
  50. let status = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
  51. let isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
  52. const res : GetBatteryInfoResult = {
  53. level: level,
  54. isCharging: isCharging
  55. };
  56. return res;
  57. }
  58. else {
  59. /**
  60. * 无有效上下文
  61. */
  62. const res : GetBatteryInfoResult = {
  63. level: -1,
  64. isCharging: false
  65. };
  66. return res;
  67. }
  68. }