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 "";
}