记录一种获取移动数据流量的方法
通过proc/net/xt_qtaguid/stats
该方法需要先获取uid,通过uid过滤出app相关的流量数据。由于项目需要采集的是移动数据流量,所以需要把lo(本地流量)和wlan(Wifi流量)筛选掉。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31public static long[] readStatsFile(Context context) {
long[] traffic = new long[2];
File localFile = new File("/proc/net/xt_qtaguid/stats");
if (localFile.exists()) {
Runtime mRuntime = Runtime.getRuntime();
try {
String line;
int uid = context.getPackageManager().getApplicationInfo(
context.getPackageName(), PackageManager.GET_ACTIVITIES).uid;
String command = "grep " + uid + " /proc/net/xt_qtaguid/stats";
Process mProcess = mRuntime.exec(command);
BufferedReader in = new BufferedReader(new InputStreamReader(
mProcess.getInputStream()));
while ((line = in.readLine()) != null) {
String[] tmp = line.split(" ");
if (tmp.length > 0 && tmp[3].equals(String.valueOf(uid))
&& !tmp[1].equals("lo") && !tmp[1].equals("wlan0") && !tmp[1].equals("wlan") && !tmp[1].equals("lo0")) {
traffic[0] = traffic[0] + Long.valueOf(tmp[5]); //下行
traffic[1] = traffic[1] + Long.valueOf(tmp[7]); //上行
} else {
continue;
}
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return traffic;
}
Android中UID,PID的区别
PID 指进程ID.
PID是进程的标识,启动应用,系统会为其主进程分配一个PID,一般来说主进程的进程名即APP的包名,当APP启动诸如,同步、推送、后台处理等等一些其他的服务或者通信进程时,系统同样会为其分配一个PID。当进程终止后PID会被系统收回,再次打开应用,会重新分配一个PID(新进程的PID一般比之前的号要大)
命令:adb shell ps | grep xxx(packagename)
图中以打开yy直播为例,可见yy存在5个进程,分别为主进程
com.duowan.mobile(24630)
和其他四个服务进程
com.duowan.mobile:yyPushService(24364)
com.duowan.mobile:sync(24108)
com.duowan.mobile:channel(23792)
com.duowan.mobile:RemoteBackgroundProcess(23866)
com.duowan.mobile:pushservice(24672)
UID 指用户ID.
UID在linux中就是用户的ID,表明时哪个用户运行了这个程序,主要用于权限的管理。
在Android 上,一个用户 UID 标示一个应用程序。应用程序在安装时被分配用户 UID,应用程序在设备上的存续期间内,用户 UID 保持不变。
命令:cat proc/PID/status
通过对上述几个PID的status文件进行查看,可以发现,在该APP下所有PID所属的UID为同一个10143。
———– The End ———–