Search in sources :

Example 71 with NetworkStats

use of android.net.NetworkStats in project Resurrection_packages_apps_Settings by ResurrectionRemix.

the class DataUsageList method bindStats.

/**
     * Bind the given {@link NetworkStats}, or {@code null} to clear list.
     */
public void bindStats(NetworkStats stats, int[] restrictedUids) {
    ArrayList<AppItem> items = new ArrayList<>();
    long largest = 0;
    final int currentUserId = ActivityManager.getCurrentUser();
    UserManager userManager = UserManager.get(getContext());
    final List<UserHandle> profiles = userManager.getUserProfiles();
    final SparseArray<AppItem> knownItems = new SparseArray<AppItem>();
    PackageManager pm = getContext().getPackageManager();
    ApplicationInfo ai = null;
    try {
        ai = pm.getApplicationInfo("com.android.dialer", PackageManager.GET_ACTIVITIES);
    } catch (Exception e) {
        Log.d(TAG, "get dialer getApplicationInfo failed " + e);
    }
    NetworkStats.Entry entry = null;
    final int size = stats != null ? stats.size() : 0;
    for (int i = 0; i < size; i++) {
        entry = stats.getValues(i, entry);
        // Decide how to collapse items together
        final int uid = entry.uid;
        final int collapseKey;
        final int category;
        final int userId = UserHandle.getUserId(uid);
        if (UserHandle.isApp(uid)) {
            if (profiles.contains(new UserHandle(userId))) {
                if (userId != currentUserId) {
                    // Add to a managed user item.
                    final int managedKey = UidDetailProvider.buildKeyForUser(userId);
                    largest = accumulate(managedKey, knownItems, entry, AppItem.CATEGORY_USER, items, largest);
                }
                // Add to app item.
                collapseKey = uid;
                category = AppItem.CATEGORY_APP;
            } else {
                // If it is a removed user add it to the removed users' key
                final UserInfo info = userManager.getUserInfo(userId);
                if (info == null) {
                    collapseKey = UID_REMOVED;
                    category = AppItem.CATEGORY_APP;
                } else {
                    // Add to other user item.
                    collapseKey = UidDetailProvider.buildKeyForUser(userId);
                    category = AppItem.CATEGORY_USER;
                }
            }
        } else if (uid == UID_REMOVED || uid == UID_TETHERING) {
            collapseKey = uid;
            category = AppItem.CATEGORY_APP;
        } else if ((ai != null) && (uid == ai.uid) && getContext().getResources().getBoolean(com.android.internal.R.bool.config_video_call_datausage_enable)) {
            collapseKey = uid;
            category = AppItem.CATEGORY_APP;
        } else {
            collapseKey = android.os.Process.SYSTEM_UID;
            category = AppItem.CATEGORY_APP;
        }
        largest = accumulate(collapseKey, knownItems, entry, category, items, largest);
    }
    final int restrictedUidsMax = restrictedUids.length;
    for (int i = 0; i < restrictedUidsMax; ++i) {
        final int uid = restrictedUids[i];
        // Only splice in restricted state for current user or managed users
        if (!profiles.contains(new UserHandle(UserHandle.getUserId(uid)))) {
            continue;
        }
        AppItem item = knownItems.get(uid);
        if (item == null) {
            item = new AppItem(uid);
            item.total = -1;
            items.add(item);
            knownItems.put(item.key, item);
        }
        item.restricted = true;
    }
    Collections.sort(items);
    mApps.removeAll();
    for (int i = 0; i < items.size(); i++) {
        final int percentTotal = largest != 0 ? (int) (items.get(i).total * 100 / largest) : 0;
        AppDataUsagePreference preference = new AppDataUsagePreference(getContext(), items.get(i), percentTotal, mUidDetailProvider);
        preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

            @Override
            public boolean onPreferenceClick(Preference preference) {
                AppDataUsagePreference pref = (AppDataUsagePreference) preference;
                AppItem item = pref.getItem();
                startAppDataUsage(item);
                return true;
            }
        });
        mApps.addPreference(preference);
    }
}
Also used : ArrayList(java.util.ArrayList) ApplicationInfo(android.content.pm.ApplicationInfo) NetworkStats(android.net.NetworkStats) UserInfo(android.content.pm.UserInfo) RemoteException(android.os.RemoteException) SparseArray(android.util.SparseArray) PackageManager(android.content.pm.PackageManager) AppItem(com.android.settingslib.AppItem) Preference(android.support.v7.preference.Preference) UserManager(android.os.UserManager) UserHandle(android.os.UserHandle)

Example 72 with NetworkStats

use of android.net.NetworkStats in project android_frameworks_base by DirtyUnicorns.

the class BandwidthTest method fetchDataFromProc.

/**
     * Fetch network data from /proc/uid_stat/uid
     *
     * @return populated {@link NetworkStats}
     */
public NetworkStats fetchDataFromProc(int uid) {
    String root_filepath = "/proc/uid_stat/" + uid + "/";
    File rcv_stat = new File(root_filepath + "tcp_rcv");
    int rx = BandwidthTestUtil.parseIntValueFromFile(rcv_stat);
    File snd_stat = new File(root_filepath + "tcp_snd");
    int tx = BandwidthTestUtil.parseIntValueFromFile(snd_stat);
    NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
    stats.addValues(NetworkStats.IFACE_ALL, uid, NetworkStats.SET_DEFAULT, NetworkStats.TAG_NONE, rx, 0, tx, 0, 0);
    return stats;
}
Also used : NetworkStats(android.net.NetworkStats) File(java.io.File)

Example 73 with NetworkStats

use of android.net.NetworkStats in project android_frameworks_base by DirtyUnicorns.

the class BandwidthTest method uploadFile.

/**
     * Helper method that downloads a test file to upload. The stats reported to instrumentation out
     * only include upload stats.
     */
protected void uploadFile() throws Exception {
    // Download a file from the server.
    String ts = Long.toString(System.currentTimeMillis());
    String targetUrl = BandwidthTestUtil.buildDownloadUrl(mTestServer, FILE_SIZE, mDeviceId, ts);
    File tmpSaveFile = new File(BASE_DIR + File.separator + TMP_FILENAME);
    assertTrue(BandwidthTestUtil.DownloadFromUrl(targetUrl, tmpSaveFile));
    ts = Long.toString(System.currentTimeMillis());
    NetworkStats pre_test_stats = fetchDataFromProc(mUid);
    TrafficStats.startDataProfiling(mContext);
    assertTrue(BandwidthTestUtil.postFileToServer(mTestServer, mDeviceId, ts, tmpSaveFile));
    NetworkStats prof_stats = TrafficStats.stopDataProfiling(mContext);
    Log.d(LOG_TAG, prof_stats.toString());
    NetworkStats post_test_stats = fetchDataFromProc(mUid);
    NetworkStats proc_stats = post_test_stats.subtract(pre_test_stats);
    // Output measurements to instrumentation out, so that it can be compared to that of
    // the server.
    Bundle results = new Bundle();
    results.putString("device_id", mDeviceId);
    results.putString("timestamp", ts);
    results.putInt("size", FILE_SIZE);
    addStatsToResults(PROF_LABEL, prof_stats, results, mUid);
    addStatsToResults(PROC_LABEL, proc_stats, results, mUid);
    getInstrumentation().sendStatus(INSTRUMENTATION_IN_PROGRESS, results);
    // Clean up.
    assertTrue(cleanUpFile(tmpSaveFile));
}
Also used : Bundle(android.os.Bundle) NetworkStats(android.net.NetworkStats) File(java.io.File)

Example 74 with NetworkStats

use of android.net.NetworkStats in project android_frameworks_base by DirtyUnicorns.

the class BandwidthTestCase method runTest.

@Override
protected void runTest() throws Throwable {
    //This is a copy of {@link InstrumentationTestCase#runTest} with
    //added logic to handle bandwidth measurements
    String fName = getName();
    assertNotNull(fName);
    Method method = null;
    Class testClass = null;
    try {
        // use getMethod to get all public inherited
        // methods. getDeclaredMethods returns all
        // methods of this class but excludes the
        // inherited ones.
        testClass = getClass();
        method = testClass.getMethod(fName, (Class[]) null);
    } catch (NoSuchMethodException e) {
        fail("Method \"" + fName + "\" not found");
    }
    if (!Modifier.isPublic(method.getModifiers())) {
        fail("Method \"" + fName + "\" should be public");
    }
    int runCount = 1;
    boolean isRepetitive = false;
    if (method.isAnnotationPresent(FlakyTest.class)) {
        runCount = method.getAnnotation(FlakyTest.class).tolerance();
    } else if (method.isAnnotationPresent(RepetitiveTest.class)) {
        runCount = method.getAnnotation(RepetitiveTest.class).numIterations();
        isRepetitive = true;
    }
    if (method.isAnnotationPresent(UiThreadTest.class)) {
        final int tolerance = runCount;
        final boolean repetitive = isRepetitive;
        final Method testMethod = method;
        final Throwable[] exceptions = new Throwable[1];
        getInstrumentation().runOnMainSync(new Runnable() {

            public void run() {
                try {
                    runMethod(testMethod, tolerance, repetitive);
                } catch (Throwable throwable) {
                    exceptions[0] = throwable;
                }
            }
        });
        if (exceptions[0] != null) {
            throw exceptions[0];
        }
    } else if (method.isAnnotationPresent(BandwidthTest.class) || testClass.isAnnotationPresent(BandwidthTest.class)) {
        /**
             * If bandwidth profiling fails for whatever reason the test
             * should be allow to execute to its completion.
             * Typically bandwidth profiling would fail when a lower level
             * component is missing, such as the kernel module, for a newly
             * introduced hardware.
             */
        try {
            TrafficStats.startDataProfiling(null);
        } catch (IllegalStateException isx) {
            Log.w(TAG, "Failed to start bandwidth profiling");
        }
        runMethod(method, 1, false);
        try {
            NetworkStats stats = TrafficStats.stopDataProfiling(null);
            NetworkStats.Entry entry = stats.getTotal(null);
            getInstrumentation().sendStatus(2, getBandwidthStats(entry));
        } catch (IllegalStateException isx) {
            Log.w(TAG, "Failed to collect bandwidth stats");
        }
    } else {
        runMethod(method, runCount, isRepetitive);
    }
}
Also used : NetworkStats(android.net.NetworkStats) Method(java.lang.reflect.Method)

Example 75 with NetworkStats

use of android.net.NetworkStats in project android_frameworks_base by DirtyUnicorns.

the class DataIdleTest method fetchStats.

/**
     * Helper method that fetches all the network stats available and reports it
     * to instrumentation out.
     * @param template {@link NetworkTemplate} to match.
     */
private void fetchStats(NetworkTemplate template) {
    INetworkStatsSession session = null;
    try {
        mStatsService.forceUpdate();
        session = mStatsService.openSession();
        final NetworkStats stats = session.getSummaryForAllUid(template, Long.MIN_VALUE, Long.MAX_VALUE, false);
        reportStats(stats);
    } catch (RemoteException e) {
        Log.w(LOG_TAG, "Failed to fetch network stats.");
    } finally {
        TrafficStats.closeQuietly(session);
    }
}
Also used : INetworkStatsSession(android.net.INetworkStatsSession) NetworkStats(android.net.NetworkStats) RemoteException(android.os.RemoteException)

Aggregations

NetworkStats (android.net.NetworkStats)271 File (java.io.File)49 DataUsageRequest (android.net.DataUsageRequest)32 Intent (android.content.Intent)29 NetworkIdentity (android.net.NetworkIdentity)28 NetworkStatsHistory (android.net.NetworkStatsHistory)21 Bundle (android.os.Bundle)18 StrictMode (android.os.StrictMode)18 ProcFileReader (com.android.internal.util.ProcFileReader)18 FileInputStream (java.io.FileInputStream)18 ProtocolException (java.net.ProtocolException)18 PendingIntent (android.app.PendingIntent)17 IOException (java.io.IOException)17 NetworkPolicy (android.net.NetworkPolicy)15 NetworkState (android.net.NetworkState)15 Test (org.junit.Test)14 Suppress (android.test.suitebuilder.annotation.Suppress)13 VpnInfo (com.android.internal.net.VpnInfo)10 RemoteException (android.os.RemoteException)8 NetworkTemplate (android.net.NetworkTemplate)6