统计网络流量,可用ActivityManager或PackageManager获取各个应用的uid,然后再用TrafficStats获取。示例如下:
private void printTrafficStat(Context context) {
long n = TrafficStats.UNSUPPORTED;
long mRxB = TrafficStats.getMobileRxBytes(); //获取通过Mobile连接收到的字节总数,不包含WiFi
long mRxP = TrafficStats.getMobileRxPackets(); //获取Mobile连接收到的数据包总数
long mTxB = TrafficStats.getMobileTxBytes(); //Mobile发送的总字节数
long mTxP = TrafficStats.getMobileTxPackets(); //Mobile发送的总数据包数
long tRxB = TrafficStats.getTotalRxBytes(); //获取总的接受字节数,包含Mobile和WiFi等
long tRxP = TrafficStats.getTotalRxPackets(); //总的接受数据包数,包含Mobile和WiFi等
long tTxB = TrafficStats.getTotalTxBytes(); //总的发送字节数,包含Mobile和WiFi等
long tTxP = TrafficStats.getTotalTxPackets(); //发送的总数据包数,包含Mobile和WiFi等
StringBuilder sb = new StringBuilder();
sb.append("mRxB:" + mRxB + ",mRxP:" + mRxP + ",mTxB:" + mTxB + ",mTxP:" + mTxP + "\n"
+ "tRxB:" + tRxB + ",tRxP:" + tRxP + ",tTxB:" + tTxB + ",tTxP:" + tTxP + "\n");
// ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
// List<ActivityManager.RunningAppProcessInfo> appList = am.getRunningAppProcesses();
// if (appList != null) {
// for (int i = 0; i < appList.size(); i++) {
// int uid = appList.get(i).uid;
// String pkg = appList.get(i).processName;
// long uRxB = TrafficStats.getUidTxBytes(uid);
// long uTxB = TrafficStats.getUidRxBytes(uid);
// sb.append("uid:" + uid + ",uRxB:" + uRxB + ",uTxB:" + uTxB + "," + pkg + "\n");
// }
// }
PackageManager pm = getPackageManager();
List<PackageInfo> piList = pm.getInstalledPackages(0);
for (PackageInfo info : piList) {
int uid = info.applicationInfo.uid;
String pkg = info.packageName;
long uRxB = TrafficStats.getUidTxBytes(uid);
long uTxB = TrafficStats.getUidRxBytes(uid);
sb.append("uid:" + uid + ",uRxB:" + uRxB + ",uTxB:" + uTxB + "," + pkg + "\n");
}
Log.i(TAG, sb.toString());
}