我正在尝试获取电池信息,主要是电源左,电压,电流为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)不能从静态上下文引用
答案 0 :(得分:1)
你有没有试过这样的事情:
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);
}
};
在你的on create方法中:
IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
mContext.registerReceiver(mBroadcastReceiver,iFilter);