我正在使用此代码跟踪我服务中的电池信息:
Intent i = new ContextWrapper(applicationContext).registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
// now you can get the level and scale from this intent variable
int level = i.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = i.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float battPct = level/(float)scale;
1.我想知道它是否会自动更改,然后更换电池?或者我是否需要定期自己解雇这个意图? 2.此外,我想知道是否有办法计算自使用1%剩余电池后经过的时间。
答案 0 :(得分:9)
获取更改价值的更好方法是使用
BroadcastReceiver
。
更换电池时更改值。您需要使用BroadCastReceiver
。
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent){
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float battPct = level/(float)scale;
}
};