2016-12-21 4 views
0

TrafficStatsの使用私はYouTubeのアプリデータの使用状況を確認していました。一部のデバイスでは正常に動作していますが、他の多くのデバイスでは動作していません。 私は開発者サイトからこれらの統計がすべてのプラットフォームで利用可能ではないことがわかりました。このデバイスで統計情報がサポートされていない場合は、UNSUPPORTEDが返されます。TrafficStatsを使用したYoutubeの使用計算

だから、これらの場合、どうすればデバイスアプリの使用を取得できますか?

私は TrafficStats.getUidRxBytes(packageInfo.uid)+ TrafficStats.getUidTxBytes(packageInfo.uid);を使用していました。

毎回-1を返します。

答えて

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

次に、特定のデバイスのロジックを変更する必要がありました。これらのデバイスでは、通常のメソッドは適切な使用値を返しません。だから私は変更されました

/* モバイルとWi-Fiの両方で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 ""; 
    } 
関連する問題