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

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

Merge "Remove data usage v1 code."

parents 61e31ab5 66cbe991
Loading
Loading
Loading
Loading
+0 −1
Original line number Diff line number Diff line
@@ -45,7 +45,6 @@ public class FeatureFlagUtils {
        DEFAULT_FLAGS.put("settings_systemui_theme", "true");
        DEFAULT_FLAGS.put("settings_dynamic_homepage", "true");
        DEFAULT_FLAGS.put("settings_mobile_network_v2", "true");
        DEFAULT_FLAGS.put("settings_data_usage_v2", "true");
        DEFAULT_FLAGS.put("settings_seamless_transfer", "false");
        DEFAULT_FLAGS.put(HEARING_AID_SETTINGS, "false");
        DEFAULT_FLAGS.put("settings_network_and_internet_v2", "false");
+0 −152
Original line number Diff line number Diff line
/*
 * Copyright (C) 2018 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.net;

import static android.net.NetworkStats.SET_DEFAULT;
import static android.net.NetworkStats.SET_FOREGROUND;
import static android.net.NetworkStats.TAG_NONE;
import static android.net.NetworkStatsHistory.FIELD_RX_BYTES;
import static android.net.NetworkStatsHistory.FIELD_TX_BYTES;
import static android.text.format.DateUtils.HOUR_IN_MILLIS;

import android.content.Context;
import android.net.INetworkStatsSession;
import android.net.NetworkStatsHistory;
import android.net.NetworkTemplate;
import android.os.Bundle;
import android.os.RemoteException;

import androidx.loader.content.AsyncTaskLoader;

import com.android.settingslib.AppItem;

/**
 * Loader for historical chart data for both network and UID details.
 *
 * Deprecated in favor of {@link NetworkCycleChartDataLoader} and
 * {@link NetworkCycleDataForUidLoader}
 *
 * @deprecated
 */
@Deprecated
public class ChartDataLoaderCompat extends AsyncTaskLoader<ChartData> {
    private static final String KEY_TEMPLATE = "template";
    private static final String KEY_APP = "app";
    private static final String KEY_FIELDS = "fields";

    private final INetworkStatsSession mSession;
    private final Bundle mArgs;

    public static Bundle buildArgs(NetworkTemplate template, AppItem app) {
        return buildArgs(template, app, FIELD_RX_BYTES | FIELD_TX_BYTES);
    }

    public static Bundle buildArgs(NetworkTemplate template, AppItem app, int fields) {
        final Bundle args = new Bundle();
        args.putParcelable(KEY_TEMPLATE, template);
        args.putParcelable(KEY_APP, app);
        args.putInt(KEY_FIELDS, fields);
        return args;
    }

    public ChartDataLoaderCompat(Context context, INetworkStatsSession session, Bundle args) {
        super(context);
        mSession = session;
        mArgs = args;
    }

    @Override
    protected void onStartLoading() {
        super.onStartLoading();
        forceLoad();
    }

    @Override
    public ChartData loadInBackground() {
        final NetworkTemplate template = mArgs.getParcelable(KEY_TEMPLATE);
        final AppItem app = mArgs.getParcelable(KEY_APP);
        final int fields = mArgs.getInt(KEY_FIELDS);

        try {
            return loadInBackground(template, app, fields);
        } catch (RemoteException e) {
            // since we can't do much without history, and we don't want to
            // leave with half-baked UI, we bail hard.
            throw new RuntimeException("problem reading network stats", e);
        }
    }

    private ChartData loadInBackground(NetworkTemplate template, AppItem app, int fields)
            throws RemoteException {
        final ChartData data = new ChartData();
        data.network = mSession.getHistoryForNetwork(template, fields);

        if (app != null) {
            // load stats for current uid and template
            final int size = app.uids.size();
            for (int i = 0; i < size; i++) {
                final int uid = app.uids.keyAt(i);
                data.detailDefault = collectHistoryForUid(
                        template, uid, SET_DEFAULT, data.detailDefault);
                data.detailForeground = collectHistoryForUid(
                        template, uid, SET_FOREGROUND, data.detailForeground);
            }

            if (size > 0) {
                data.detail = new NetworkStatsHistory(data.detailForeground.getBucketDuration());
                data.detail.recordEntireHistory(data.detailDefault);
                data.detail.recordEntireHistory(data.detailForeground);
            } else {
                data.detailDefault = new NetworkStatsHistory(HOUR_IN_MILLIS);
                data.detailForeground = new NetworkStatsHistory(HOUR_IN_MILLIS);
                data.detail = new NetworkStatsHistory(HOUR_IN_MILLIS);
            }
        }

        return data;
    }

    @Override
    protected void onStopLoading() {
        super.onStopLoading();
        cancelLoad();
    }

    @Override
    protected void onReset() {
        super.onReset();
        cancelLoad();
    }

    /**
     * Collect {@link NetworkStatsHistory} for the requested UID, combining with
     * an existing {@link NetworkStatsHistory} if provided.
     */
    private NetworkStatsHistory collectHistoryForUid(
            NetworkTemplate template, int uid, int set, NetworkStatsHistory existing)
            throws RemoteException {
        final NetworkStatsHistory history = mSession.getHistoryForUid(
                template, uid, set, TAG_NONE, FIELD_RX_BYTES | FIELD_TX_BYTES);

        if (existing != null) {
            existing.recordEntireHistory(history);
            return existing;
        } else {
            return history;
        }
    }
}
+2 −68
Original line number Diff line number Diff line
@@ -32,30 +32,24 @@ import android.net.INetworkStatsService;
import android.net.INetworkStatsSession;
import android.net.NetworkPolicy;
import android.net.NetworkPolicyManager;
import android.net.NetworkStatsHistory;
import android.net.NetworkTemplate;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.text.format.DateUtils;
import android.util.FeatureFlagUtils;
import android.util.Log;
import android.util.Range;

import com.android.internal.R;
import com.android.internal.annotations.VisibleForTesting;

import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;

public class DataUsageController {

    private static final String TAG = "DataUsageController";
    @VisibleForTesting
    static final String DATA_USAGE_V2 = "settings_data_usage_v2";
    private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
    private static final int FIELDS = FIELD_RX_BYTES | FIELD_TX_BYTES;
    private static final StringBuilder PERIOD_BUILDER = new StringBuilder(50);
@@ -95,21 +89,6 @@ public class DataUsageController {
                * mContext.getResources().getInteger(R.integer.default_data_warning_level_mb);
    }

    @VisibleForTesting
    @Deprecated
    INetworkStatsSession getSession() {
        if (mSession == null) {
            try {
                mSession = mStatsService.openSession();
            } catch (RemoteException e) {
                Log.w(TAG, "Failed to open stats session", e);
            } catch (RuntimeException e) {
                Log.w(TAG, "Failed to open stats session", e);
            }
        }
        return mSession;
    }

    public void setCallback(Callback callback) {
        mCallback = callback;
    }
@@ -149,13 +128,7 @@ public class DataUsageController {
            end = now;
            start = now - DateUtils.WEEK_IN_MILLIS * 4;
        }
        final long totalBytes;
        final long callStart = System.currentTimeMillis();
        if (FeatureFlagUtils.isEnabled(mContext, DATA_USAGE_V2)) {
            totalBytes = getUsageLevel(template, start, end);
        } else {
            totalBytes = getUsageLevel(template, start, end, now);
        }
        final long totalBytes = getUsageLevel(template, start, end);
        if (totalBytes < 0L) {
            return warn("no entry data");
        }
@@ -185,32 +158,7 @@ public class DataUsageController {
     * retrieving the data.
     */
    public long getHistoricalUsageLevel(NetworkTemplate template) {
        if (FeatureFlagUtils.isEnabled(mContext, DATA_USAGE_V2)) {
        return getUsageLevel(template, 0L /* start */, System.currentTimeMillis() /* end */);
        } else {
            final long now = System.currentTimeMillis();
            return getUsageLevel(template, 0L /* start */, now /* end */, now);
        }
    }

    @Deprecated
    private long getUsageLevel(NetworkTemplate template, long start, long end, long now) {
        final INetworkStatsSession session = getSession();
        if (session != null) {
            try {
                final NetworkStatsHistory history =
                    session.getHistoryForNetwork(template, FIELDS);
                final NetworkStatsHistory.Entry entry = history.getValues(
                        start, end, System.currentTimeMillis() /* now */, null /* recycle */);
                if (entry != null) {
                    return entry.rxBytes + entry.txBytes;
                }
                Log.w(TAG, "Failed to get data usage, no entry data");
            } catch (RemoteException e) {
                Log.w(TAG, "Failed to get data usage, remote call failed");
            }
        }
        return -1L;
    }

    private long getUsageLevel(NetworkTemplate template, long start, long end) {
@@ -241,20 +189,6 @@ public class DataUsageController {
        return null;
    }

    @Deprecated
    private static String historyEntryToString(NetworkStatsHistory.Entry entry) {
        return entry == null ? null : new StringBuilder("Entry[")
                .append("bucketDuration=").append(entry.bucketDuration)
                .append(",bucketStart=").append(entry.bucketStart)
                .append(",activeTime=").append(entry.activeTime)
                .append(",rxBytes=").append(entry.rxBytes)
                .append(",rxPackets=").append(entry.rxPackets)
                .append(",txBytes=").append(entry.txBytes)
                .append(",txPackets=").append(entry.txPackets)
                .append(",operations=").append(entry.operations)
                .append(']').toString();
    }

    private static String statsBucketToString(Bucket bucket) {
        return bucket == null ? null : new StringBuilder("Entry[")
            .append("bucketDuration=").append(bucket.getEndTimeStamp() - bucket.getStartTimeStamp())
+0 −87
Original line number Diff line number Diff line
/*
 * Copyright (C) 2018 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.net;

import android.content.Context;
import android.net.INetworkStatsSession;
import android.net.NetworkStats;
import android.net.NetworkTemplate;
import android.os.Bundle;
import android.os.RemoteException;

import androidx.loader.content.AsyncTaskLoader;

/**
 * Deprecated in favor of {@link NetworkStatsDetailLoader}
 *
 * @deprecated
 */
@Deprecated
public class SummaryForAllUidLoaderCompat extends AsyncTaskLoader<NetworkStats> {
    private static final String KEY_TEMPLATE = "template";
    private static final String KEY_START = "start";
    private static final String KEY_END = "end";

    private final INetworkStatsSession mSession;
    private final Bundle mArgs;

    public static Bundle buildArgs(NetworkTemplate template, long start, long end) {
        final Bundle args = new Bundle();
        args.putParcelable(KEY_TEMPLATE, template);
        args.putLong(KEY_START, start);
        args.putLong(KEY_END, end);
        return args;
    }

    public SummaryForAllUidLoaderCompat(Context context, INetworkStatsSession session,
            Bundle args) {
        super(context);
        mSession = session;
        mArgs = args;
    }

    @Override
    protected void onStartLoading() {
        super.onStartLoading();
        forceLoad();
    }

    @Override
    public NetworkStats loadInBackground() {
        final NetworkTemplate template = mArgs.getParcelable(KEY_TEMPLATE);
        final long start = mArgs.getLong(KEY_START);
        final long end = mArgs.getLong(KEY_END);

        try {
            return mSession.getSummaryForAllUid(template, start, end, false);
        } catch (RemoteException e) {
            return null;
        }
    }

    @Override
    protected void onStopLoading() {
        super.onStopLoading();
        cancelLoad();
    }

    @Override
    protected void onReset() {
        super.onReset();
        cancelLoad();
    }
}
+11 −64
Original line number Diff line number Diff line
@@ -18,7 +18,6 @@ package com.android.settingslib.net;

import static com.google.common.truth.Truth.assertThat;

import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.anyLong;
@@ -35,12 +34,10 @@ import android.content.Context;
import android.net.ConnectivityManager;
import android.net.INetworkStatsSession;
import android.net.NetworkStatsHistory;
import android.net.NetworkStatsHistory.Entry;
import android.net.NetworkTemplate;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.text.format.DateUtils;
import android.util.FeatureFlagUtils;

import org.junit.Before;
import org.junit.Test;
@@ -48,7 +45,6 @@ import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;

@RunWith(RobolectricTestRunner.class)
public class DataUsageControllerTest {
@@ -61,16 +57,18 @@ public class DataUsageControllerTest {
    private TelephonyManager mTelephonyManager;
    @Mock
    private NetworkStatsManager mNetworkStatsManager;

    @Mock
    private Context mContext;

    private DataUsageController mController;
    private NetworkStatsHistory mNetworkStatsHistory;

    @Before
    public void setUp() throws RemoteException {
        MockitoAnnotations.initMocks(this);
        mContext = RuntimeEnvironment.application;
        mController = spy(new DataUsageController(mContext));
        when(mContext.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn(mTelephonyManager);
        when(mContext.getSystemService(NetworkStatsManager.class)).thenReturn(mNetworkStatsManager);
        mController = new DataUsageController(mContext);
        mNetworkStatsHistory = spy(
                new NetworkStatsHistory(DateUtils.DAY_IN_MILLIS /* bucketDuration */));
        doReturn(mNetworkStatsHistory)
@@ -79,75 +77,25 @@ public class DataUsageControllerTest {
    }

    @Test
    public void getHistoricalUsageLevel_v1_noNetworkSession_shouldReturnNegative1() {
        FeatureFlagUtils.setEnabled(mContext, DataUsageController.DATA_USAGE_V2, false);
        doReturn(null).when(mController).getSession();

        assertThat(mController.getHistoricalUsageLevel(null /* template */)).isEqualTo(-1L);
    }

    @Test
    public void getHistoriclUsageLevel_v1_noUsageData_shouldReturn0() {
        FeatureFlagUtils.setEnabled(mContext, DataUsageController.DATA_USAGE_V2, false);
        doReturn(mSession).when(mController).getSession();

        assertThat(mController.getHistoricalUsageLevel(NetworkTemplate.buildTemplateWifiWildcard()))
                .isEqualTo(0L);
    }

    @Test
    public void getHistoricalUsageLevel_v1_hasUsageData_shouldReturnTotalUsage() {
        FeatureFlagUtils.setEnabled(mContext, DataUsageController.DATA_USAGE_V2, false);
        doReturn(mSession).when(mController).getSession();
        final long receivedBytes = 743823454L;
        final long transmittedBytes = 16574289L;
        final Entry entry = new Entry();
        entry.bucketStart = 1521583200000L;
        entry.rxBytes = receivedBytes;
        entry.txBytes = transmittedBytes;
        when(mNetworkStatsHistory.getValues(eq(0L), anyLong(), anyLong(), nullable(Entry.class)))
                .thenReturn(entry);

        assertThat(mController.getHistoricalUsageLevel(NetworkTemplate.buildTemplateWifiWildcard()))
                .isEqualTo(receivedBytes + transmittedBytes);
    }

    @Test
    public void getHistoricalUsageLevel_v2_shouldQuerySummaryForDevice() throws Exception {
        final Context context = mock(Context.class);
        FeatureFlagUtils.setEnabled(context, DataUsageController.DATA_USAGE_V2, true);
        when(context.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn(mTelephonyManager);
        when(context.getSystemService(NetworkStatsManager.class)).thenReturn(mNetworkStatsManager);
        final DataUsageController controller = new DataUsageController(context);
    public void getHistoricalUsageLevel_shouldQuerySummaryForDevice() throws Exception {

        controller.getHistoricalUsageLevel(NetworkTemplate.buildTemplateWifiWildcard());
        mController.getHistoricalUsageLevel(NetworkTemplate.buildTemplateWifiWildcard());

        verify(mNetworkStatsManager).querySummaryForDevice(eq(ConnectivityManager.TYPE_WIFI),
                eq(SUB_ID), eq(0L) /* startTime */, anyLong() /* endTime */);
    }

    @Test
    public void getHistoricalUsageLevel_v2NoUsageData_shouldReturn0() throws Exception {
        final Context context = mock(Context.class);
        FeatureFlagUtils.setEnabled(context, DataUsageController.DATA_USAGE_V2, true);
        when(context.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn(mTelephonyManager);
        when(context.getSystemService(NetworkStatsManager.class)).thenReturn(mNetworkStatsManager);
    public void getHistoricalUsageLevel_noUsageData_shouldReturn0() throws Exception {
        when(mNetworkStatsManager.querySummaryForDevice(eq(ConnectivityManager.TYPE_WIFI),
                eq(SUB_ID), eq(0L) /* startTime */, anyLong() /* endTime */))
                .thenReturn(mock(NetworkStats.Bucket.class));
        final DataUsageController controller = new DataUsageController(context);

        assertThat(controller.getHistoricalUsageLevel(NetworkTemplate.buildTemplateWifiWildcard()))
        assertThat(mController.getHistoricalUsageLevel(NetworkTemplate.buildTemplateWifiWildcard()))
            .isEqualTo(0L);
    }

    @Test
    public void getHistoricalUsageLevel_v2HasUsageData_shouldReturnTotalUsage()
            throws Exception {
        final Context context = mock(Context.class);
        FeatureFlagUtils.setEnabled(context, DataUsageController.DATA_USAGE_V2, true);
        when(context.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn(mTelephonyManager);
        when(context.getSystemService(NetworkStatsManager.class)).thenReturn(mNetworkStatsManager);
    public void getHistoricalUsageLevel_hasUsageData_shouldReturnTotalUsage() throws Exception {
        final long receivedBytes = 743823454L;
        final long transmittedBytes = 16574289L;
        final NetworkStats.Bucket bucket = mock(NetworkStats.Bucket.class);
@@ -155,9 +103,8 @@ public class DataUsageControllerTest {
        when(bucket.getTxBytes()).thenReturn(transmittedBytes);
        when(mNetworkStatsManager.querySummaryForDevice(eq(ConnectivityManager.TYPE_WIFI),
                eq(SUB_ID), eq(0L) /* startTime */, anyLong() /* endTime */)).thenReturn(bucket);
        final DataUsageController controller = new DataUsageController(context);

        assertThat(controller.getHistoricalUsageLevel(NetworkTemplate.buildTemplateWifiWildcard()))
        assertThat(mController.getHistoricalUsageLevel(NetworkTemplate.buildTemplateWifiWildcard()))
                .isEqualTo(receivedBytes + transmittedBytes);
    }
}