Android平台在2.2版本之后,系统提供了TrafficStats类来实现流量的统计。
它是根据每个应用的UID来进行划分。
/** *流量统计 */ private void FlowCount() { // TODO Auto-generated method stub AlertDialog.Builder builder = new AlertDialog.Builder(SettingActivity.this); builder.setTitle("流量使用情况:"); //PackageManager 包管理类 PackageManager packageManager = getPackageManager(); int PackageUid = 0; long totalRx = 0; long totalTx = 0; long totalFlow = 0; /** * 循环抓紧所有应用的包名 * 和当前应用的包名进行匹配操作 * 把获取到的UID保存到一个临时变量 */ for(ApplicationInfo info : packageManager.getInstalledApplications(0)){ int uid = info.uid; String packageName = info.packageName; if(packageName.equals("com.easier.assistant")){ PackageUid = uid; } } //TrafficStats类根据应用的UID获取到流量的相关数据 long recv = TrafficStats.getUidRxBytes(PackageUid); long sent = TrafficStats.getUidTxBytes(PackageUid); if(sent>0){ totalTx += sent/1024; if(totalTx>=1024) totalTx = totalTx/1024; } if(recv>0){ totalRx += recv/1024; if(totalRx>=1024) totalRx = totalRx/1024; } totalFlow = totalRx + totalTx; if(totalFlow>=1024){ totalFlow = totalFlow/1024; builder.setMessage("总使用流量:"+totalFlow+"M"); }else { builder.setMessage("总使用流量:"+totalFlow+"K"); } builder.create(); builder.show(); }