我正在尝试计算电池充电或放电率。我使用 ACTION_BATTERY_CHANGED 来接收事件并等待至少 1% 的变化。然后我将电池电量的差异除以时间(毫秒)的差异。我将结果乘以 1000 * 60 * 60 以显示“每小时单位百分比”的速率。但我不确定我做得对还是有一些错误。因为,有时它会显示大约 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;
}
}