Move BatteryInfo to settings from settingslib

This CL simply moves BatteryInfo from settingslib to settings and
makes sure the tests still pass. No other changes are made other than
imports or minor changes needed to make sure existing code does not
break.

Test: Robotests still pass
Bug: 38399275
Bug: 38398949
Bug: 38399654
Change-Id: I59803348e2780b7676ccc6c43234a586c184d71f
This commit is contained in:
Salvador Martinez
2017-05-31 17:18:23 -07:00
parent 51333ec21f
commit 0e8c88376c
12 changed files with 483 additions and 17 deletions

View File

@@ -19,7 +19,6 @@ import android.telephony.ServiceState;
import android.util.SparseIntArray;
import com.android.settings.Utils;
import com.android.settings.fuelgauge.BatteryActiveView.BatteryActiveProvider;
import com.android.settingslib.BatteryInfo;
public class BatteryCellParser implements BatteryInfo.BatteryDataParser, BatteryActiveProvider {

View File

@@ -18,7 +18,6 @@ import android.os.BatteryStats.HistoryItem;
import android.util.SparseBooleanArray;
import android.util.SparseIntArray;
import com.android.settings.fuelgauge.BatteryActiveView.BatteryActiveProvider;
import com.android.settingslib.BatteryInfo;
public class BatteryFlagParser implements BatteryInfo.BatteryDataParser, BatteryActiveProvider {

View File

@@ -27,7 +27,6 @@ import android.widget.TextView;
import com.android.settings.R;
import com.android.settings.applications.LayoutPreference;
import com.android.settings.core.PreferenceController;
import com.android.settingslib.BatteryInfo;
import com.android.settingslib.Utils;
/**

View File

@@ -40,7 +40,6 @@ import android.util.TypedValue;
import android.view.View;
import com.android.settings.R;
import com.android.settings.Utils;
import com.android.settingslib.BatteryInfo;
import libcore.icu.LocaleData;
import java.util.ArrayList;

View File

@@ -31,7 +31,6 @@ import com.android.internal.os.BatteryStatsHelper;
import com.android.settings.R;
import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.fuelgauge.BatteryActiveView.BatteryActiveProvider;
import com.android.settingslib.BatteryInfo;
import com.android.settingslib.graph.UsageView;
public class BatteryHistoryDetail extends SettingsPreferenceFragment {

View File

@@ -17,7 +17,6 @@
package com.android.settings.fuelgauge;
import android.content.Context;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.VisibleForTesting;
import android.support.v7.preference.Preference;
@@ -26,9 +25,6 @@ import android.util.AttributeSet;
import android.widget.TextView;
import com.android.internal.os.BatteryStatsHelper;
import com.android.settings.R;
import com.android.settings.Utils;
import com.android.settings.overlay.FeatureFactory;
import com.android.settingslib.BatteryInfo;
import com.android.settingslib.graph.UsageView;
/**

View File

@@ -0,0 +1,314 @@
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.android.settings.fuelgauge;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.BatteryManager;
import android.os.BatteryStats;
import android.os.BatteryStats.HistoryItem;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.format.Formatter;
import android.util.SparseIntArray;
import com.android.internal.os.BatteryStatsHelper;
import com.android.settingslib.R;
import com.android.settingslib.Utils;
import com.android.settingslib.graph.UsageView;
public class BatteryInfo {
public String chargeLabelString;
public int batteryLevel;
public boolean discharging = true;
public long remainingTimeUs = 0;
public String batteryPercentString;
public String remainingLabel;
public String statusLabel;
private boolean mCharging;
private BatteryStats mStats;
private long timePeriod;
public interface Callback {
void onBatteryInfoLoaded(BatteryInfo info);
}
public void bindHistory(final UsageView view, BatteryDataParser... parsers) {
BatteryDataParser parser = new BatteryDataParser() {
SparseIntArray points = new SparseIntArray();
@Override
public void onParsingStarted(long startTime, long endTime) {
timePeriod = endTime - startTime - remainingTimeUs / 1000;
view.clearPaths();
view.configureGraph((int) (endTime - startTime), 100, remainingTimeUs != 0,
mCharging);
}
@Override
public void onDataPoint(long time, HistoryItem record) {
points.put((int) time, record.batteryLevel);
}
@Override
public void onDataGap() {
if (points.size() > 1) {
view.addPath(points);
}
points.clear();
}
@Override
public void onParsingDone() {
if (points.size() > 1) {
view.addPath(points);
}
}
};
BatteryDataParser[] parserList = new BatteryDataParser[parsers.length + 1];
for (int i = 0; i < parsers.length; i++) {
parserList[i] = parsers[i];
}
parserList[parsers.length] = parser;
parse(mStats, remainingTimeUs, parserList);
final Context context = view.getContext();
String timeString = context.getString(R.string.charge_length_format,
Formatter.formatShortElapsedTime(context, timePeriod));
String remaining = "";
if (remainingTimeUs != 0) {
remaining = context.getString(R.string.remaining_length_format,
Formatter.formatShortElapsedTime(context, remainingTimeUs / 1000));
}
view.setBottomLabels(new CharSequence[]{timeString, remaining});
}
public static void getBatteryInfo(final Context context, final Callback callback) {
BatteryInfo.getBatteryInfo(context, callback, false /* shortString */);
}
public static void getBatteryInfo(final Context context, final Callback callback,
boolean shortString) {
new AsyncTask<Void, Void, BatteryStats>() {
@Override
protected BatteryStats doInBackground(Void... params) {
BatteryStatsHelper statsHelper = new BatteryStatsHelper(context, true);
statsHelper.create((Bundle) null);
return statsHelper.getStats();
}
@Override
protected void onPostExecute(BatteryStats batteryStats) {
final long elapsedRealtimeUs = SystemClock.elapsedRealtime() * 1000;
Intent batteryBroadcast = context.registerReceiver(null,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
BatteryInfo batteryInfo = BatteryInfo.getBatteryInfo(context, batteryBroadcast,
batteryStats, elapsedRealtimeUs, shortString);
callback.onBatteryInfoLoaded(batteryInfo);
}
}.execute();
}
public static BatteryInfo getBatteryInfo(Context context, Intent batteryBroadcast,
BatteryStats stats, long elapsedRealtimeUs) {
return BatteryInfo.getBatteryInfo(context, batteryBroadcast, stats, elapsedRealtimeUs,
false /* shortString */);
}
public static BatteryInfo getBatteryInfo(Context context, Intent batteryBroadcast,
BatteryStats stats, long elapsedRealtimeUs, boolean shortString) {
return getBatteryInfo(context, batteryBroadcast, stats, elapsedRealtimeUs, shortString,
stats.computeBatteryTimeRemaining(elapsedRealtimeUs), false);
}
public static BatteryInfo getBatteryInfo(Context context, Intent batteryBroadcast,
BatteryStats stats, long elapsedRealtimeUs, boolean shortString, long drainTimeUs,
boolean basedOnUsage) {
BatteryInfo info = new BatteryInfo();
info.mStats = stats;
info.batteryLevel = Utils.getBatteryLevel(batteryBroadcast);
info.batteryPercentString = Utils.formatPercentage(info.batteryLevel);
info.mCharging = batteryBroadcast.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0;
final Resources resources = context.getResources();
info.statusLabel = Utils.getBatteryStatus(resources, batteryBroadcast);
if (!info.mCharging) {
if (drainTimeUs > 0) {
info.remainingTimeUs = drainTimeUs;
String timeString = Formatter.formatShortElapsedTime(context,
drainTimeUs / 1000);
info.remainingLabel = resources.getString(
shortString ?
(basedOnUsage ?
R.string.power_remaining_duration_only_short_enhanced :
R.string.power_remaining_duration_only_short) :
(basedOnUsage ?
R.string.power_remaining_duration_only_enhanced :
R.string.power_remaining_duration_only),
timeString);
info.chargeLabelString = resources.getString(
shortString ?
R.string.power_discharging_duration_short :
basedOnUsage ?
R.string.power_discharging_duration_enhanced :
R.string.power_discharging_duration,
info.batteryPercentString, timeString);
} else {
info.remainingLabel = null;
info.chargeLabelString = info.batteryPercentString;
}
} else {
final long chargeTime = stats.computeChargeTimeRemaining(elapsedRealtimeUs);
final int status = batteryBroadcast.getIntExtra(BatteryManager.EXTRA_STATUS,
BatteryManager.BATTERY_STATUS_UNKNOWN);
info.discharging = false;
if (chargeTime > 0 && status != BatteryManager.BATTERY_STATUS_FULL) {
info.remainingTimeUs = chargeTime;
String timeString = Formatter.formatShortElapsedTime(context,
chargeTime / 1000);
int resId = shortString ? R.string.power_charging_duration_short
: R.string.power_charging_duration;
info.remainingLabel = resources.getString(
R.string.power_remaining_charging_duration_only, timeString);
info.chargeLabelString = resources.getString(
resId, info.batteryPercentString, timeString);
} else {
final String chargeStatusLabel = resources.getString(
R.string.battery_info_status_charging_lower);
info.remainingLabel = null;
info.chargeLabelString = resources.getString(
R.string.power_charging, info.batteryPercentString, chargeStatusLabel);
}
}
return info;
}
public interface BatteryDataParser {
void onParsingStarted(long startTime, long endTime);
void onDataPoint(long time, HistoryItem record);
void onDataGap();
void onParsingDone();
}
private static void parse(BatteryStats stats, long remainingTimeUs,
BatteryDataParser... parsers) {
long startWalltime = 0;
long endDateWalltime = 0;
long endWalltime = 0;
long historyStart = 0;
long historyEnd = 0;
byte lastLevel = -1;
long curWalltime = startWalltime;
long lastWallTime = 0;
long lastRealtime = 0;
int lastInteresting = 0;
int pos = 0;
boolean first = true;
if (stats.startIteratingHistoryLocked()) {
final HistoryItem rec = new HistoryItem();
while (stats.getNextHistoryLocked(rec)) {
pos++;
if (first) {
first = false;
historyStart = rec.time;
}
if (rec.cmd == HistoryItem.CMD_CURRENT_TIME
|| rec.cmd == HistoryItem.CMD_RESET) {
// If there is a ridiculously large jump in time, then we won't be
// able to create a good chart with that data, so just ignore the
// times we got before and pretend like our data extends back from
// the time we have now.
// Also, if we are getting a time change and we are less than 5 minutes
// since the start of the history real time, then also use this new
// time to compute the base time, since whatever time we had before is
// pretty much just noise.
if (rec.currentTime > (lastWallTime + (180 * 24 * 60 * 60 * 1000L))
|| rec.time < (historyStart + (5 * 60 * 1000L))) {
startWalltime = 0;
}
lastWallTime = rec.currentTime;
lastRealtime = rec.time;
if (startWalltime == 0) {
startWalltime = lastWallTime - (lastRealtime - historyStart);
}
}
if (rec.isDeltaData()) {
if (rec.batteryLevel != lastLevel || pos == 1) {
lastLevel = rec.batteryLevel;
}
lastInteresting = pos;
historyEnd = rec.time;
}
}
}
stats.finishIteratingHistoryLocked();
endDateWalltime = lastWallTime + historyEnd - lastRealtime;
endWalltime = endDateWalltime + (remainingTimeUs / 1000);
int i = 0;
final int N = lastInteresting;
for (int j = 0; j < parsers.length; j++) {
parsers[j].onParsingStarted(startWalltime, endWalltime);
}
if (endDateWalltime > startWalltime && stats.startIteratingHistoryLocked()) {
final HistoryItem rec = new HistoryItem();
while (stats.getNextHistoryLocked(rec) && i < N) {
if (rec.isDeltaData()) {
curWalltime += rec.time - lastRealtime;
lastRealtime = rec.time;
long x = (curWalltime - startWalltime);
if (x < 0) {
x = 0;
}
for (int j = 0; j < parsers.length; j++) {
parsers[j].onDataPoint(x, rec);
}
} else {
long lastWalltime = curWalltime;
if (rec.cmd == HistoryItem.CMD_CURRENT_TIME
|| rec.cmd == HistoryItem.CMD_RESET) {
if (rec.currentTime >= startWalltime) {
curWalltime = rec.currentTime;
} else {
curWalltime = startWalltime + (rec.time - historyStart);
}
lastRealtime = rec.time;
}
if (rec.cmd != HistoryItem.CMD_OVERFLOW
&& (rec.cmd != HistoryItem.CMD_CURRENT_TIME
|| Math.abs(lastWalltime - curWalltime) > (60 * 60 * 1000))) {
for (int j = 0; j < parsers.length; j++) {
parsers[j].onDataGap();
}
}
}
i++;
}
}
stats.finishIteratingHistoryLocked();
for (int j = 0; j < parsers.length; j++) {
parsers[j].onParsingDone();
}
}
}

View File

@@ -24,7 +24,6 @@ import android.content.Intent;
import android.content.IntentFilter;
import android.content.Loader;
import android.content.res.TypedArray;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
@@ -42,13 +41,11 @@ import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceGroup;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.format.Formatter;
import android.util.Log;
import android.util.SparseArray;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.internal.os.BatterySipper;
@@ -72,7 +69,6 @@ import com.android.settings.fuelgauge.anomaly.AnomalyLoader;
import com.android.settings.fuelgauge.anomaly.AnomalySummaryPreferenceController;
import com.android.settings.overlay.FeatureFactory;
import com.android.settings.search.BaseSearchIndexProvider;
import com.android.settingslib.BatteryInfo;
import com.android.settingslib.widget.FooterPreferenceMixin;
import java.util.ArrayList;

View File

@@ -27,7 +27,6 @@ import static org.mockito.Mockito.verify;
import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceScreen;
import android.widget.TextView;
@@ -37,7 +36,6 @@ import com.android.settings.TestConfig;
import com.android.settings.applications.LayoutPreference;
import com.android.settings.testutils.shadow.SettingsShadowResources;
import com.android.settings.testutils.shadow.ShadowDynamicIndexableContentMonitor;
import com.android.settingslib.BatteryInfo;
import org.junit.Before;
import org.junit.Test;

View File

@@ -30,7 +30,6 @@ import android.widget.TextView;
import com.android.settings.R;
import com.android.settings.SettingsRobolectricTestRunner;
import com.android.settings.TestConfig;
import com.android.settingslib.BatteryInfo;
import com.android.settingslib.graph.UsageView;
import org.junit.Before;

View File

@@ -0,0 +1,169 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.fuelgauge;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.BatteryManager;
import android.os.BatteryStats;
import android.os.SystemClock;
import com.android.settings.TestConfig;
import com.android.settingslib.R;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.AdditionalMatchers.*;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
public class BatteryInfoTest {
private static final String STATUS_FULL = "Full";
private static final String STATUS_CHARGING_NO_TIME = "Charging";
private static final String STATUS_CHARGING_TIME = "Charging - 2h left";
private static final int PLUGGED_IN = 1;
private static final long REMAINING_TIME_NULL = -1;
private static final long REMAINING_TIME = 2;
public static final String ENHANCED_STRING_SUFFIX = "left based on your usage";
private Intent mDisChargingBatteryBroadcast;
private Intent mChargingBatteryBroadcast;
private Context mRealContext;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private BatteryStats mBatteryStats;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Context mContext;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Resources mResources;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mDisChargingBatteryBroadcast = new Intent();
mDisChargingBatteryBroadcast.putExtra(BatteryManager.EXTRA_PLUGGED, 0);
mDisChargingBatteryBroadcast.putExtra(BatteryManager.EXTRA_LEVEL, 0);
mDisChargingBatteryBroadcast.putExtra(BatteryManager.EXTRA_SCALE, 100);
mDisChargingBatteryBroadcast.putExtra(BatteryManager.EXTRA_STATUS,
BatteryManager.BATTERY_STATUS_FULL);
mChargingBatteryBroadcast = new Intent();
mChargingBatteryBroadcast.putExtra(BatteryManager.EXTRA_PLUGGED,
BatteryManager.BATTERY_PLUGGED_AC);
mChargingBatteryBroadcast.putExtra(BatteryManager.EXTRA_LEVEL, 50);
mChargingBatteryBroadcast.putExtra(BatteryManager.EXTRA_SCALE, 100);
mChargingBatteryBroadcast.putExtra(BatteryManager.EXTRA_STATUS,
BatteryManager.BATTERY_STATUS_UNKNOWN);
when(mContext.getResources().getString(R.string.battery_info_status_full))
.thenReturn(STATUS_FULL);
when(mContext.getResources().getString(eq(R.string.power_charging), any(),
any())).thenReturn(STATUS_CHARGING_NO_TIME);
when(mContext.getResources().getString(eq(R.string.power_charging_duration), any(),
any())).thenReturn(STATUS_CHARGING_TIME);
mRealContext = RuntimeEnvironment.application;
}
@Test
public void testGetBatteryInfo_hasStatusLabel() {
doReturn(REMAINING_TIME_NULL).when(mBatteryStats).computeBatteryTimeRemaining(anyLong());
BatteryInfo info = BatteryInfo.getBatteryInfo(mContext, mDisChargingBatteryBroadcast,
mBatteryStats, SystemClock.elapsedRealtime() * 1000, true /* shortString */);
assertThat(info.statusLabel).isEqualTo(STATUS_FULL);
}
@Test
public void testGetBatteryInfo_doNotShowChargingMethod_hasRemainingTime() {
doReturn(REMAINING_TIME).when(mBatteryStats).computeChargeTimeRemaining(anyLong());
BatteryInfo info = BatteryInfo.getBatteryInfo(mContext, mChargingBatteryBroadcast,
mBatteryStats, SystemClock.elapsedRealtime() * 1000, false /* shortString */);
assertThat(info.chargeLabelString).isEqualTo(STATUS_CHARGING_TIME);
}
@Test
public void testGetBatteryInfo_doNotShowChargingMethod_noRemainingTime() {
doReturn(REMAINING_TIME_NULL).when(mBatteryStats).computeChargeTimeRemaining(anyLong());
BatteryInfo info = BatteryInfo.getBatteryInfo(mContext, mChargingBatteryBroadcast,
mBatteryStats, SystemClock.elapsedRealtime() * 1000, false /* shortString */);
assertThat(info.chargeLabelString).isEqualTo(STATUS_CHARGING_NO_TIME);
}
@Test
public void testGetBatteryInfo_pluggedIn_dischargingFalse() {
BatteryInfo info = BatteryInfo.getBatteryInfo(mContext, mChargingBatteryBroadcast,
mBatteryStats, SystemClock.elapsedRealtime() * 1000, true /* shortString */);
assertThat(info.discharging).isEqualTo(false);
}
@Test
public void testGetBatteryInfo_basedOnUsageTrue_usesUsageString() {
doReturn(mResources).when(mContext).getResources();
when(mResources.getString(eq(R.string.battery_info_status_full))).thenReturn("");
when(mResources.getString(eq(R.string.power_remaining_duration_only_enhanced), any()))
.thenReturn(ENHANCED_STRING_SUFFIX);
when(mResources.getString(eq(R.string.power_remaining_duration_only_short_enhanced), any()))
.thenReturn(ENHANCED_STRING_SUFFIX);
BatteryInfo info = BatteryInfo.getBatteryInfo(mContext, mDisChargingBatteryBroadcast,
mBatteryStats, SystemClock.elapsedRealtime() * 1000, false /* shortString */,
1000, true /* basedOnUsage */);
BatteryInfo info2 = BatteryInfo.getBatteryInfo(mContext, mDisChargingBatteryBroadcast,
mBatteryStats, SystemClock.elapsedRealtime() * 1000, true /* shortString */,
1000, true /* basedOnUsage */);
assertThat(info.remainingLabel).contains(ENHANCED_STRING_SUFFIX);
assertThat(info2.remainingLabel).contains(ENHANCED_STRING_SUFFIX);
}
@Test
public void testGetBatteryInfo_basedOnUsageFalse_usesDefaultString() {
doReturn(mResources).when(mContext).getResources();
when(mResources.getString(eq(R.string.battery_info_status_full))).thenReturn("");
when(mResources.getString(not(eq(R.string.power_remaining_duration_only_enhanced)), any()))
.thenReturn(ENHANCED_STRING_SUFFIX);
when(mResources.getString(not(eq(R.string.power_remaining_duration_only_short_enhanced)),
any())).thenReturn("");
BatteryInfo info = BatteryInfo.getBatteryInfo(mContext, mDisChargingBatteryBroadcast,
mBatteryStats, SystemClock.elapsedRealtime() * 1000, false /* shortString */,
1000, false /* basedOnUsage */);
BatteryInfo info2 = BatteryInfo.getBatteryInfo(mContext, mDisChargingBatteryBroadcast,
mBatteryStats, SystemClock.elapsedRealtime() * 1000, true /* shortString */,
1000, false /* basedOnUsage */);
assertThat(info.remainingLabel).doesNotContain(ENHANCED_STRING_SUFFIX);
assertThat(info2.remainingLabel).doesNotContain(ENHANCED_STRING_SUFFIX);
}
}

View File

@@ -47,7 +47,6 @@ import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.shadow.SettingsShadowResources;
import com.android.settings.testutils.shadow.ShadowDynamicIndexableContentMonitor;
import com.android.settings.testutils.XmlTestUtils;
import com.android.settingslib.BatteryInfo;
import org.junit.Before;
import org.junit.Test;