android 获取移动网络,Android获取移动当前APP移动流量的方法

记录一种获取移动数据流量的方法

通过proc/net/xt_qtaguid/stats

该方法需要先获取uid,通过uid过滤出app相关的流量数据。由于项目需要采集的是移动数据流量,所以需要把lo(本地流量)和wlan(Wifi流量)筛选掉。

1.png

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)

2.png

图中以打开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

3.png

通过对上述几个PID的status文件进行查看,可以发现,在该APP下所有PID所属的UID为同一个10143。

———– The End ———–

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值