如何使用Nativescript获得手机的续航能力?

时间:2018-07-11 07:30:54

标签: nativescript

我尝试使用本机脚本,但这种方法无效:

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

console.log("battery level: ", Math.floor(this.battery.level * 100) + "%");

1 个答案:

答案 0 :(得分:3)

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

对于android,您可以注册ACTION_BATTERY_CHANGED的broadcastreciever。对于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;
    });
}