uniapp 获取Android手机和苹果手机电量
onLoad() {
let res = uni.getSystemInfoSync()
if (res.platform === 'android' && plus) {
var main = plus.android.runtimeMainActivity();
var Intent = plus.android.importClass('android.content.Intent');
var recevier = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
onReceive: function(context, intent) {
var action = intent.getAction();
if (action == Intent.ACTION_BATTERY_CHANGED) {
var level = intent.getIntExtra("level", 0); //电量
var voltage = intent.getIntExtra("voltage", 0); //电池电压
var temperature = intent.getIntExtra("temperature", 0); //电池温度
//如需获取别的,在这里继续写,此代码只提供获取电量
// + %
console.log(level)
}
}
});
var IntentFilter = plus.android.importClass('android.content.IntentFilter');
var filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
main.registerReceiver(recevier, filter);
} else if (res.platform === 'ios' && plus) {
var UIDevice = plus.ios.import("UIDevice");
var dev = UIDevice.currentDevice();
if (!dev.isBatteryMonitoringEnabled()) {
dev.setBatteryMonitoringEnabled(true);
}
// 电量 *100 +%
var level = dev.batteryLevel();
console.log(level)
}
},
结果: Android 94 ,ios 0.94