Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit d86a0ca6 authored by TreeHugger Robot's avatar TreeHugger Robot Committed by Android (Google) Code Review
Browse files

Merge "Remove BatteryInfo from settingslib"

parents 1f1a2740 cf298ebc
Loading
Loading
Loading
Loading
+0 −312
Original line number Diff line number Diff line
/*
 * 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.settingslib;

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.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();
        }
    }
}
+0 −168
Original line number Diff line number Diff line
/*
 * 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.settingslib;

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 org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.AdditionalMatchers;
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);
    }
}
+1 −31
Original line number Diff line number Diff line
@@ -20,9 +20,6 @@ import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.service.quicksettings.Tile;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
@@ -35,9 +32,7 @@ import android.widget.Switch;
import android.widget.TextView;

import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.settingslib.BatteryInfo;
import com.android.settingslib.graph.BatteryMeterDrawableBase;
import com.android.settingslib.graph.UsageView;
import com.android.systemui.Dependency;
import com.android.systemui.R;
import com.android.systemui.plugins.qs.DetailAdapter;
@@ -187,14 +182,6 @@ public class BatterySaverTile extends QSTileImpl<BooleanState> implements
            ((ImageView) mCurrentView.findViewById(android.R.id.icon)).setImageDrawable(mDrawable);
            Checkable checkbox = (Checkable) mCurrentView.findViewById(android.R.id.toggle);
            checkbox.setChecked(mPowerSave);
            BatteryInfo.getBatteryInfo(mContext, new BatteryInfo.Callback() {
                @Override
                public void onBatteryInfoLoaded(BatteryInfo info) {
                    if (mCurrentView != null) {
                        bindBatteryInfo(info);
                    }
                }
            });
            final TextView batterySaverTitle =
                    (TextView) mCurrentView.findViewById(android.R.id.title);
            final TextView batterySaverSummary =
@@ -216,23 +203,6 @@ public class BatterySaverTile extends QSTileImpl<BooleanState> implements
            }
        }

        private void bindBatteryInfo(BatteryInfo info) {
            SpannableStringBuilder builder = new SpannableStringBuilder();
            builder.append(info.batteryPercentString, new RelativeSizeSpan(2.6f),
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            if (info.remainingLabel != null) {
                if (mContext.getResources().getBoolean(R.bool.quick_settings_wide)) {
                    builder.append(' ');
                } else {
                    builder.append('\n');
                }
                builder.append(info.remainingLabel);
            }
            ((TextView) mCurrentView.findViewById(R.id.charge_and_estimation)).setText(builder);

            info.bindHistory((UsageView) mCurrentView.findViewById(R.id.battery_usage));
        }

        @Override
        public void onClick(View v) {
            mBatteryController.setPowerSaveMode(!mPowerSave);