【问题标题】:Youtube usage calculation using TrafficStats使用 TrafficStats 计算 Youtube 使用情况
【发布时间】:2017-05-07 04:49:24
【问题描述】:

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

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

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

这每次都返回 -1。

【问题讨论】:

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


    【解决方案1】:

    我们可以使用 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 "";
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-17
      • 1970-01-01
      • 1970-01-01
      • 2016-07-07
      • 2011-07-04
      • 1970-01-01
      • 2023-03-27
      相关资源
      最近更新 更多