我正在尝试计算电池充电或放电率。我使用ACTION_BATTERY_CHANGED来接收事件,我等待至少1%的更改。然后我将电池电量差异除以时间差(毫秒)。我将结果乘以1000 * 60 * 60以“%per hour unit”显示比率。但我不确定我是做得对还是有些错误。因为,有时它显示充电或放电约6%或15%,这似乎是正确的。但有时它显示大约15000%。
所以有人可以告诉我这段代码有什么问题。
这是我的代码:
注册:
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(new EnReceiverOnBatteryChange(), batteryLevelFilter)
接收器:
public class EnReceiverOnBatteryChange extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Utils.recordChargeOrDischargeRate(context);
ActivityHome.updateBatteryInfo(context);
}
}
计算:
public static void recordChargeOrDischargeRate(Context context)
{
long lCurrentTime = System.currentTimeMillis();
float fCurrentBatteryLevel = 0;
float fRate = 0;
if ((mfLastBatteryLevel != -1) && (mlLastTime != -1))
{
SharedPreferences preferences = context.getSharedPreferences(Konstant.PREFERENCES_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor prefEditor = preferences.edit();
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
if (level != -1 && scale != -1)
{
fCurrentBatteryLevel = 100 * level / (float) scale;
}
float fBatteryLevelDifference = Math.abs(fCurrentBatteryLevel - mfLastBatteryLevel);
if (fBatteryLevelDifference > 0.99)
{
fRate = (fBatteryLevelDifference / (lCurrentTime - mlLastTime)) * 1000 * 60;
prefEditor.putString(Konstant.KEY_PREF_CHARGING_START_RATE, String.format("%.2f", (fRate * 60)) + "%");
prefEditor.commit();
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = (status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL);
if (isCharging)
{
int nMinutes = Math.round((100 - fCurrentBatteryLevel) / fRate);
int nHour = nMinutes / 60;
nMinutes = nMinutes % 60;
prefEditor.putString(Konstant.KEY_PREF_FULL_CHARGE_IN, nHour + "h " + nMinutes + "m");
prefEditor.commit();
}
else
{
int nMinutes = Math.round(fCurrentBatteryLevel / fRate);
int nHour = nMinutes / 60;
nMinutes = nMinutes % 60;
prefEditor.putString(Konstant.KEY_PREF_FULL_CHARGE_IN, nHour + "h " + nMinutes + "m");
prefEditor.commit();
}
mlLastTime = lCurrentTime;
mfLastBatteryLevel = fCurrentBatteryLevel;
}
}
else
{
mlLastTime = lCurrentTime;
mfLastBatteryLevel = fCurrentBatteryLevel;
}
}
答案 0 :(得分:0)
看一下android选项中的电池状态图。手机的能源使用率有时会在较小的时间尺度上发生巨大变化 - 尽管在较大的时间范围内它看起来是恒定的。 我可能错了,但也许你应该更好地寻找几分钟的时差,而不是1%的电池电量差。