1

使用 TrafficStats 我正在检查 youtube 应用程序数据使用情况。在某些设备上它工作正常,但在许多其他设备上却不行。我从开发者网站发现,这些统计数据可能并非在所有平台上都可用。如果此设备不支持统计信息,将返回 UNSUPPORTED。

那么在这些情况下,我怎样才能获得设备应用程序的使用情况?

我正在使用 TrafficStats.getUidRxBytes(packageInfo.uid) + TrafficStats.getUidTxBytes(packageInfo.uid);

这每次都返回-1。

4

1 回答 1

0

我们可以使用 NetworkStats。 https://developer.android.com/reference/android/app/usage/NetworkStats.html 请查看我得到线索的示例存储库。 https://github.com/RobertZagorski/NetworkStats 我们也可以看到类似的 stackoverflow 问题。 使用 NetworkStatsManager 获取移动数据使用历史记录

然后我需要为一些特定的设备修改这个逻辑。在这些设备中,正常方法不会返回正确的使用值。所以我修改为

/* 获取移动设备和 wifi 的 youtube 使用情况。*/

    public long getYoutubeTotalusage(Context context) {
            String subId = getSubscriberId(context, ConnectivityManager.TYPE_MOBILE);

//both mobile and wifi usage is calculating. For mobile usage we need subscriberid. For wifi we can give it as empty string value.
            return getYoutubeUsage(ConnectivityManager.TYPE_MOBILE, subId) + getYoutubeUsage(ConnectivityManager.TYPE_WIFI, "");
        }


private long getYoutubeUsage(int networkType, String subScriberId) {
        NetworkStats networkStatsByApp;
        long currentYoutubeUsage = 0L;
        try {
            networkStatsByApp = networkStatsManager.querySummary(networkType, subScriberId, 0, System.currentTimeMillis());
            do {
                NetworkStats.Bucket bucket = new NetworkStats.Bucket();
                networkStatsByApp.getNextBucket(bucket);
                if (bucket.getUid() == packageUid) {
                    //rajeesh : in some devices this is immediately looping twice and the second iteration is returning correct value. So result returning is moved to the end.
                    currentYoutubeUsage = (bucket.getRxBytes() + bucket.getTxBytes());
                }
            } while (networkStatsByApp.hasNextBucket());

        } catch (RemoteException e) {
            e.printStackTrace();
        }

        return currentYoutubeUsage;
    }


    private String getSubscriberId(Context context, int networkType) {
        if (ConnectivityManager.TYPE_MOBILE == networkType) {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            return tm.getSubscriberId();
        }
        return "";
    }
于 2017-01-17T11:32:37.410 回答