以编程方式获取 android 电池信息
Getting android battery information programmatically
我正在尝试获取 android N(7.1.1) 设备的电池信息,主要是剩余电量、电压、电流。我正在尝试 运行 onCreate 方法中的以下代码。
第一种方法;
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
batteryStatus = this.registerReceiver(null, ifilter);
double currentNow = BatteryManager.BATTERY_PROPERTY_CURRENT_NOW;
double voltage = BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE;
double level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
double scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE,
第二种方法:
BatteryManager mBatteryManager =
(BatteryManager)Context.getSystemService(Context.BATTERY_SERVICE);
Long energy =
mBatteryManager.getLongProperty(BatteryManager.BATTERY_PROPERTY_ENERGY_COUNTER);
第一种方法给我默认值,第二种方法给我错误:无法从静态上下文中引用非静态方法 getsystemservice(string)
你有没有尝试过这样的事情:
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get the battery scale
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE,-1);
// get the battery level
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL,-1);
}
};
并且在您的创建方法中:
IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
mContext.registerReceiver(mBroadcastReceiver,iFilter);
我正在尝试获取 android N(7.1.1) 设备的电池信息,主要是剩余电量、电压、电流。我正在尝试 运行 onCreate 方法中的以下代码。
第一种方法;
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
batteryStatus = this.registerReceiver(null, ifilter);
double currentNow = BatteryManager.BATTERY_PROPERTY_CURRENT_NOW;
double voltage = BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE;
double level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
double scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE,
第二种方法:
BatteryManager mBatteryManager =
(BatteryManager)Context.getSystemService(Context.BATTERY_SERVICE);
Long energy =
mBatteryManager.getLongProperty(BatteryManager.BATTERY_PROPERTY_ENERGY_COUNTER);
第一种方法给我默认值,第二种方法给我错误:无法从静态上下文中引用非静态方法 getsystemservice(string)
你有没有尝试过这样的事情:
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get the battery scale
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE,-1);
// get the battery level
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL,-1);
}
};
并且在您的创建方法中:
IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
mContext.registerReceiver(mBroadcastReceiver,iFilter);