当前位置: 首页 > 科技观察

Android应用源码流量监控

时间:2023-03-23 12:01:55 科技观察

源码介绍在网上找到的一个小例子,可以统计各个应用的网络流量,区分移动网络和WIFI技术要点:使用TrafficStats记录流量变化使用Service、BroadcastReceiver监测网络状态变化使用sqlite记录使用流量每个应用的数据(只能统计应用安装后使用的流量,不能统计之前使用的流量)。源码运行截图代码片段:@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);txtView=(TextView)findViewById(R.id.textView1);Intentintent=newIntent(MainActivity.this,TrafficService.class);bindService(intent,mConnection,Context.BIND_AUTO_CREATE);dbManager=newDbManager(this);findViewById(R.id.button1).setOnClickListener(newOnClickListener(){@OverridepublicvoidonClick(Viewv){if(trafficService==null){txtView.setText("服务未绑定");}else{trafficService.logRecord();Maplist=dbManager.queryTotal();StringBuildersb=newStringBuilder();for(TrafficInfoinfo:list.values()){sb.append(info.appName+"-流量信息:\r\n");sb.append("移动网络接收到的流量"+Formatter.formatFileSize(MainActivity.this,info.mobileRx)).append("\r\n");sb.append("移动网络发送的流量"+Formatter.formatFileSize(MainActivity.this,info.mobileTx)).append("\r\n");sb.append("WIFI接收流量"+Formatter.formatFileSize(MainActivity.this,info.wifiRx)).append("\r\n");sb.append("WIFI发送流量"+Formatter.formatFileSize(MainActivity.this,info.wifiTx)).append("\r\n");sb.append("--------------------").append("\r\n");txtView.setText(sb);}}}});}源链接:http://down.51cto.com/900943