android 其实就是linux 上面包装了一个java的框架.
linux 系统下 所有的硬件,设备 都是以文件的方式来表示.
文件里面包含的有很多设备的状态信息.
所有的流量相关的信息 都是记录在文件上的.
注意:模拟器 是不支持流量查询的.
proc 系统的状态信息
adb -s 3835197E43F100EC shell
在uid_stat 的目录下有一堆文件夹
名字是以应用程序的uid作为名字的. app 46 就是10046
内容就是这个应用程序 上传和下载产生的流量信息
tcp_rcv 采用tcp协议 接收到的数据的大小
tcp receive
tcp_snd 采用tcp协议 发送的数据的byte大小
snd send
tcp_rcv_pkt 采用tcp协议 接收到的包的数目
流量信息 : 上一次开机到现在这个程序产生的流量 .
package cn.itcast.testtraffic;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.net.TrafficStats;
import android.os.Bundle;
import android.widget.TextView;
public class DemoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
/* long mobilerx = TrafficStats.getMobileRxBytes();
long mobiletx = TrafficStats.getMobileTxBytes();
StringBuilder sb = new StringBuilder();
long mobiletotal = mobilerx+mobiletx;
sb.append("2g/3g总流量"+ TextFormater.getDataSize(mobiletotal));
sb.append("\n");
long totalrx = TrafficStats.getTotalRxBytes();
long toatltx = TrafficStats.getTotalTxBytes();
long total = toatltx+ totalrx;
long wifitotal = total-mobiletotal;
sb.append("wifi总流量"+ TextFormater.getDataSize(wifitotal));
sb.append("\n");
TextView tv = new TextView(this);
tv.setText(sb.toString());
setContentView(tv);*/
// 在手机里面得到所有的产生图标的应用程序
//TrafficStats.getUidRxBytes(uid);
PackageManager pm = getPackageManager();
Intent intent = new Intent();
intent.setAction("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
List<ResolveInfo> resovleInfos = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for(ResolveInfo info : resovleInfos){
String appname = info.loadLabel(pm).toString();
System.out.println("appname "+ appname);
Drawable appicon = info.loadIcon(pm);
String packname = info.activityInfo.packageName;
try {
PackageInfo packinfo = pm.getPackageInfo(packname, 0);
int uid = packinfo.applicationInfo.uid;
System.out.println("下载流量"+ TextFormater.getDataSize( TrafficStats.getUidRxBytes(uid)));
System.out.println("上传流量"+ TextFormater.getDataSize( TrafficStats.getUidTxBytes(uid)));
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("------");
}
}
}