android 利用TrafficStats类获取本应用的流量
public void getData() { // PackageManager 包管理类 PackageManager packageManager = BrownserActivity.this.getPackageManager(); int PackageUid = 0; BigDecimal numRx = new BigDecimal("0"); BigDecimal numTx = new BigDecimal("0"); /** * 循环抓紧所有应用的包名 和当前应用的包名进行匹配操作 把获取到的UID保存到一个临时变量 */ /*for (ApplicationInfo info : packageManager.getInstalledApplications(0)) { int uid = info.uid; String packageName = info.packageName; if (packageName.indexOf("iAssistant") > -1) { PackageUid = uid; break; } }*/ // 获取当前应用的uid PackageUid = android.os.Process.myUid(); // TrafficStats类根据应用的UID获取到流量的相关数据 long rx = TrafficStats.getUidRxBytes(PackageUid);// 总接收量 long tx = TrafficStats.getUidTxBytes(PackageUid);// 总发送量 float justLoad = 0f; Log.i("scott", "本应用本次开机总接收量:" + rx); Log.i("scott", "本应用本次开机总发送量:" + tx); if (rx > 0) { numRx = byteToM(rx); justLoad = numRx.floatValue() - initData; initData = numRx.floatValue(); } if (tx > 0) { numTx = byteToM(tx); } // Toast.makeText(BrownserActivity.this, "总接收量:"+numRx.floatValue()+"M", // Toast.LENGTH_SHORT).show(); Toast.makeText(BrownserActivity.this, "本次接收量:" + justLoad + "M", Toast.LENGTH_SHORT).show(); Log.i("scott", "转换为(M为单位)后的总接收量:" + numRx.floatValue()); Log.i("scott", "转换为(M为单位)后的总发送量:" + numTx.floatValue()); } /** * 字节转换为M */ private BigDecimal byteToM(long value) { BigDecimal result = new BigDecimal(Long.toString(value)); result = result.divide(new BigDecimal("1024.0")).divide(new BigDecimal("1024.0")); return result; }
本文来自博客园,作者:mushishi,转载请注明原文链接:https://www.cnblogs.com/mushishi/p/3880463.html