Android6.0 及以上设备查看流量使用情况

Android About 2,589 words

所需权限

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions"/>

初始化 NetworkStatsManager

mNetworkStatsManager = (NetworkStatsManager) context.getSystemService(NETWORK_STATS_SERVICE);
 // 获取subscriberId
 TelephonyManager tm = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
 try {
     mSubId = tm.getSubscriberId();
 } catch (Exception e) {
     mSubId = "";
     e.printStackTrace();
 }
  • 获取月初到目前为止设备的Mobile流量统计
public long getMobileFlow() {
    long mobileFlow = 0;
    try {
        NetworkStats.Bucket bucket;
        bucket = mNetworkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_MOBILE, mSubId, getTimesMonthMorning(), System.currentTimeMillis());
        mobileFlow = bucket.getRxBytes() + bucket.getTxBytes();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return mobileFlow;
}
  • 获取单个应用月初到目前为止设备的WiFi流量统计
private long getWiFiFlowByUid(int uid){
    NetworkStats summaryStats;
    NetworkStats.Bucket summaryBucket = new NetworkStats.Bucket();
    long summaryTotal = 0;
    try {
        summaryStats = mNetworkStatsManager.queryDetailsForUid(
                ConnectivityManager.TYPE_WIFI, mSubId, 0, System.currentTimeMillis(),uid);
        do {
            summaryStats.getNextBucket(summaryBucket);
            summaryTotal += summaryBucket.getRxBytes() + summaryBucket.getTxBytes();
        } while (summaryStats.hasNextBucket());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return summaryTotal;
}
  • 获取单个应用月初到目前为止设备的Mobile流量统计
private long getMobileFlowByUid(int uid){
    NetworkStats summaryStats;
    NetworkStats.Bucket summaryBucket = new NetworkStats.Bucket();
    long summaryTotal = 0;

    try {
        summaryStats = mNetworkStatsManager.queryDetailsForUid(
                ConnectivityManager.TYPE_MOBILE, mSubId, 0, System.currentTimeMillis(),uid);
        do {
            summaryStats.getNextBucket(summaryBucket);
            summaryTotal += summaryBucket.getRxBytes() + summaryBucket.getTxBytes();
        } while (summaryStats.hasNextBucket());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return summaryTotal;
}
  • 获取月初的毫秒值
private long getTimesMonthMorning() {
    Calendar cal = Calendar.getInstance();
    cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
    cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
    return cal.getTimeInMillis();
}
Views: 5,992 · Posted: 2019-04-13

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh