使用TrafficStats进行Youtube使用计算

时间:2016-12-21 17:09:56

标签: android youtube network-traffic android-data-usage

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

因此,在这些情况下,我如何才能获得设备应用?

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

每次都返回-1。

1 个答案:

答案 0 :(得分:0)

我们可以使用NetworkStats。 https://developer.android.com/reference/android/app/usage/NetworkStats.html 请查看我得到线索的样本回购。 https://github.com/RobertZagorski/NetworkStats 我们也可以看到类似的stackoverflow问题。 Getting mobile data usage history using 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 "";
    }