如何使用 Nativescript 获得手机的电源寿命?

Ume*_*per -1 nativescript

我尝试使用这样的 nativescript 但它不起作用:

battery = navigator.battery || navigator.webkitBattery || navigator.mozBattery || navigator.msBattery;

console.log("battery level: ", Math.floor(this.battery.level * 100) + "%");
Run Code Online (Sandbox Code Playgroud)

bha*_*ara 5

您必须编写相应的本机代码来获取电池信息。

对于 android,您可以注册广播接收器ACTION_BATTERY_CHANGED。对于 ios,您可以使用UIDevice.currentDevice.batteryLevel

例子:

import { android as androidApp, ios as iosApp } from "application";
import { ios as iosUtils } from "utils/utils";

if (iosApp){
  iosUtils.getter(UIDevice, UIDevice.currentDevice).batteryMonitoringEnabled = true;
  let battery = +(iosUtils.getter(UIDevice, UIDevice.currentDevice).batteryLevel * 100);
}else{
  androidApp.registerBroadcastReceiver(android.content.Intent.ACTION_BATTERY_CHANGED,(context: android.content.Context, intent: android.content.Intent) =>{
        let level = intent.getIntExtra(android.os.BatteryManager.EXTRA_LEVEL, -1);
        let scale = intent.getIntExtra(android.os.BatteryManager.EXTRA_SCALE, -1);
        let percent = (level / scale) * 100.0;
    });
}
Run Code Online (Sandbox Code Playgroud)