这个类提供了网络流量统计,这个统计包括上传和下载的字节数和网络数据包数。需要注意的是这个统计不能在所有的平台上使用,如果设备不支持的话,就会返回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() 发送的数据包总数,包括流量和WIFI
public static long getTotalRxPackets() 接收的数据包总数,包括流量和WIFI