这个类提供了网络流量统计,这个统计包括上传和下载的字节数和网络数据包数。需要注意的是这个统计不能在所有的平台上使用,如果设备不支持的话,就会返回UNSUPPORTED。

常用函数:

public static void setThreadStatsTag(int tag)public static int getThreadStatsTag()public static void clearThreadStatsTag()public static void tagSocket(Socket socket)public static void untagSocket(Socket socket)

在android 4.0.4的sdk DDMS中,有了一个工具:Network Traffic Tool 。通过这个工具可以实时地监测网络的使用情况,使程序员更好的发现自己的应用程序在什么时候发送接收了多少的网络数据.

如果要更加清楚地看清每一个网络连接的使用情况可以在程序中对网络连接打tag,如对socket连接可以这样:

TrafficStats.setThreadStatsTag(0xF00D);
TrafficStats.tagSocket(outputSocket);
// Transfer data using socket
TrafficStats.untagSocket(outputSocket);

对于Apache HttpClient and URLConnection 会自动打上tag,所以只要设置上tag名就可以了:

对于Apache HttpClient and URLConnection 会自动打上tag,所以只要设置上tag名就可以了:TrafficStats.setThreadStatsTag(0xF00D);
try {// Make network request using HttpClient.execute()
} finally {TrafficStats.clearThreadStatsTag();
}

其他函数:

public static void incrementOperationCount(int operationCount)public static void incrementOperationCount(int tag, int operationCount)

增加网络操作的数量

public static long getMobileTxPackets()   通过流量发送的数据包数public static long getMobileRxPackets() 通过流量接收到的数据包数public static long getMobileTxBytes()  通过流量发送的字节数public static long getMobileRxBytes()  通过流量接收的字节数public static long getTotalTxPackets()  发送的数据包总数,包括流量和WIFIpublic static long getTotalRxPackets()  接收的数据包总数,包括流量和WIFIpublic static long getTotalTxBytes()  发送的字节总数,包括流量和WIFIpublic static long getTotalRxBytes()  接收的字节总数,包括流量和WIFIpublic static long getUidTxPackets(int uid) 获取指定网络UID发送的数据包数public static long getUidRxPackets(int uid)  获取指定网络UID接收的数据包数public static long getUidTxBytes(int uid)  获取指定网络UID发送的字节数public static long getUidRxBytes(int uid)  获取指定网络UID接收的字节数

下面写一个小demo

MainActivity.java

package com.xxx.cn.trafficstatstest;import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.TrafficStats;
import android.os.Bundle;
import android.widget.ListView;import java.util.ArrayList;
import java.util.List;public class MainActivity extends Activity {private List apps = new ArrayList <ApplicationBean>();private ListView mListView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mListView = (ListView) findViewById(R.id.lv_app);getAppTrafficStatList();MyAdapter adapter = new MyAdapter(apps, this);mListView.setAdapter(adapter);}public void getAppTrafficStatList() {PackageManager pm = getPackageManager();//得到安装的所以应用List<PackageInfo> pinfos = pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES |PackageManager.GET_PERMISSIONS);//找出需要网络权限的应用,得到这个应用上传和下载的数据量for (PackageInfo info : pinfos) {String[] pers = info.requestedPermissions;if (pers != null && pers.length > 0) {for (String per : pers)//找到需要网络权限的应用if ("android.permission.INTERNET".equals(per)) {int uid = info.applicationInfo.uid;String lable = (String) info.applicationInfo.loadLabel(pm);Drawable icon = null;try {icon = pm.getApplicationIcon(info.packageName);} catch (PackageManager.NameNotFoundException e) {e.printStackTrace();}long rx = TrafficStats.getUidRxBytes(uid);long tx = TrafficStats.getUidTxBytes(uid);ApplicationBean app = new ApplicationBean();app.setName(lable);app.setIcon(icon);app.setRx(rx);app.setTx(tx);apps.add(app);}}}}}

MyAdapter.java

package com.xxx.cn.trafficstatstest;import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;import java.util.List;public class MyAdapter extends BaseAdapter {private List mApps;private LayoutInflater inflater;public MyAdapter(List apps, Context context) {this.mApps = apps;this.inflater = LayoutInflater.from(context);}@Overridepublic int getCount() {return mApps.size();}@Overridepublic Object getItem(int position) {return mApps.get(position);}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {ViewHolder view;if (convertView == null) {convertView = inflater.inflate(R.layout.app_item, null);view = new ViewHolder();view.name = (TextView) convertView.findViewById(R.id.app_name);view.icon = (ImageView) convertView.findViewById(R.id.app_icon);view.rx = (TextView) convertView.findViewById(R.id.app_rx);view.tx = (TextView) convertView.findViewById(R.id.app_tx);convertView.setTag(view);} else {view = (ViewHolder) convertView.getTag();}ApplicationBean app = (ApplicationBean) mApps.get(position);view.name.setText(app.getName());view.icon.setImageDrawable(app.getIcon());view.rx.setText("接收:" + app.getRx());view.tx.setText("上传:" + app.getTx());return convertView;}public static class ViewHolder {public TextView name;public ImageView icon;public TextView rx;public TextView tx;}
}

ApplicationBean.java

package com.xxx.cn.trafficstatstest;import android.graphics.drawable.Drawable;public class ApplicationBean {private String name;private Drawable icon;private long rx;private long tx;public String getName() {return name;}public void setName(String name) {this.name = name;}public Drawable getIcon() {return icon;}public void setIcon(Drawable icon) {this.icon = icon;}public long getTx() {return tx;}public void setTx(long tx) {this.tx = tx;}public long getRx() {return rx;}public void setRx(long rx) {this.rx = rx;}
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><ListView
        android:id="@+id/lv_app"android:layout_width="match_parent"android:layout_height="match_parent" /></RelativeLayout>

app_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal"android:layout_width="match_parent"android:padding="10dp"android:layout_height="wrap_content"><ImageView
        android:id="@+id/app_icon"android:layout_width="wrap_content"android:layout_height="wrap_content" /><LinearLayout
        android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"><TextView
            android:id="@+id/app_name"android:layout_width="wrap_content"android:layout_height="wrap_content" /><TextView
            android:id="@+id/app_tx"android:layout_width="wrap_content"android:layout_height="wrap_content" /><TextView
            android:id="@+id/app_rx"android:layout_width="wrap_content"android:layout_height="wrap_content" /></LinearLayout></LinearLayout>

运行界面如下:

Android中TrafficStats流量监控类相关推荐

  1. android流量监控软件设计与实现,基于android平台的流量监控系统的设计与实现

    摘要: 为了解决流量超额使用,恶意流量吸费的非法插件以及软件恶意联网的问题,帮助用户安全放心使用手机,本文设计并实现了一款基于Android平台的流量监控系统. 本文以Android系统为平台,分别从 ...

  2. Android中对话框的工具类

    Android中对话框的工具类,里面总结了比较好用的方法,直接调用即可 public class DialogUtils {private DialogUtils() {}private static ...

  3. fritz 使用手册_Fritz对象检测指南:使用机器学习在Android中构建宠物监控应用

    fritz 使用手册 by Eric Hsiao 萧敬轩 Fritz对象检测指南:使用机器学习在Android中构建宠物监控应用 (A guide to Object Detection with F ...

  4. android如何开发流量监控软件

    http://xlover.iteye.com/blog/1358301 最近在测试中经常要去查看一个进程的流量.所以了解了一下这方面的知识!在此总结一下 Android流量监控主要是有两种方法: 一 ...

  5. 360 android系统 流量,360手机卫士Android版增流量监控

    2011-3-15 10:52 [天极网IT新闻频道]目前,随着Android手机系统大热,低价智能手机越来越普及,而智能机最大的特点就是软件丰富和可随时随地可以上网.地铁里发微博,看新闻甚至看视频都 ...

  6. 360 android系统 流量,警惕天价流量费 360手机卫士Android版增流量监控

    目前,随着Android手机系统大热,低价智能手机越来越普及,而智能机最大的特点就是软件丰富和可随时随地可以上网.地铁里发微博,看新闻甚至看视频都成为很多朋友的一大爱好.但是,也有不少初次使用智能手机 ...

  7. Android中怎样在工具类中获取Context对象

    场景 Android程序中访问资源时需要提供Context,一般来说只有在各种component中(Activity, Provider等等)才能方便的使用api来获取Context对象, 如果在编写 ...

  8. android 开发工具类,Android中常用开发工具类—持续更新...

    一.自定义ActionBar public class ActionBarTool { public static void setActionBarLayout(Activity act,Conte ...

  9. Android中少用枚举类(enum)而多用,泪目

    你的函数可以接受连续的数据 用于名称 other- 4. 不使用枚举类型的解决方案 ========================================================== ...

最新文章

  1. 【JavaScript从入门到精通】第一课 初探JavaScript魅力-01
  2. select BUGS
  3. CV】keras_resnet 在cifar10数据集上分类
  4. java判断44数组是否是4阶幻方_2015蓝桥杯决赛Java A组 第二题--四阶幻方
  5. akka2.5_播放2.0:Akka,Rest,Json和依赖项
  6. 深入理解JavaScript之Event Loop
  7. java-线程-生产者-消费者
  8. Bootstrap 禁用的按钮
  9. 分享几套古典复古式的UI设计
  10. 杭电计算机2016年机试真题详解
  11. 双非计算机考研复试怎么办,【计算机考研】985、211VS双非,复试时导师会有歧视吗?...
  12. 【台词】严厉的愛Tough Love」(后妈茶话会)
  13. J1939协议之通俗易懂----简介
  14. VC++_2010_学习版_下载教程
  15. TV_Control Android机顶盒手机控制全套程序开源
  16. sql计算字段中字数的个数
  17. 【BZOJ3162】独钓寒江雪(树哈希,动态规划)
  18. tp5.1 出现Class 'Qcloud\Sms\SmsSingleSender' not found(mac和windows没有,linux出现)
  19. sql 创建学生表 课程表 成绩表
  20. python sympy包符号运算进行定积分计算

热门文章

  1. 华为S2300 配置
  2. 软阈值 (Soft Thresholding)函数解读
  3. 深度学习Pytorch框架
  4. iphone计算机怎么修改错误字体,终于能给iPhone修改字体了,无需越狱,仅限iOS12.4...
  5. 动态大奖赛和CRM解决方案时间表说明
  6. 【FPGA-DSP】第九期:音频信号处理
  7. MSM8909 CW2015 电量计驱动调试
  8. 实力与颜值并存 —— Apache Pulsar PMC 成员刘昱专访
  9. 今年某宝网双11“喵糖游戏”又翻车了?遭大量网友举报
  10. 基于Springboot的幼儿园管理系统