在Activity实时显示当前APP所耗网速 TrafficStats.getUidRxBytes

	private long total_data;
	private Handler mHandler;
	private int uid = -1;

	/**
	 * 定义线程周期性地获取网速
	 */
	private Runnable mRunnable = new Runnable() {
		@Override
		public void run() {
			// 定时器
			mHandler.postDelayed(mRunnable, 5000);
			Message msg = mHandler.obtainMessage();
			msg.what = 1;
			msg.arg1 = getNetSpeed();
			mHandler.sendMessage(msg);
		}
	};
	
	private int getNetSpeed() {
		long traffic_data = TrafficStats.getUidRxBytes(uid) - total_data;
		total_data = TrafficStats.getUidRxBytes(uid);
		return (int) traffic_data / 5;
	}
	
	private void netSpeedInit() {
		netSpeed.setText(" ");
		uid = getPackageUid();
		total_data = TrafficStats.getUidRxBytes(uid);
		
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				
				if (msg.what == 1) {
					netSpeed.setText(msg.arg1 / 1024 + "." + (msg.arg1 % 1024) / 103 + "Kb/s");
				}
			}
		};
		
		if (uid != -1) {
			mHandler.postDelayed(mRunnable, 5000);
		}
	}
	
	private int getPackageUid() {
		try {
			PackageManager pm = getPackageManager();
			ApplicationInfo ai = pm.getApplicationInfo(
					"lelink.Android",
					PackageManager.GET_ACTIVITIES);

			LOG.i("" + ai.uid);
			return ai.uid;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		
		return -1;
	}

其中netSpeed为TextView,pm.getApplictaionInfo()中替换你的包名,在你的Activity的onCreate()里调用netSpeedInit()函数即可。


以下为TrafficStats类常用的一些统计流量的方法:

static long  getMobileRxBytes()  //获取通过Mobile连接收到的字节总数,不包含WiFi  
static long  getMobileRxPackets()  //获取Mobile连接收到的数据包总数  
static long  getMobileTxBytes()  //Mobile发送的总字节数  
static long  getMobileTxPackets()  //Mobile发送的总数据包数  
static long  getTotalRxBytes()  //获取总的接受字节数,包含Mobile和WiFi等  
static long  getTotalRxPackets()  //总的接受数据包数,包含Mobile和WiFi等  
static long  getTotalTxBytes()  //总的发送字节数,包含Mobile和WiFi等  
static long  getTotalTxPackets()  //发送的总数据包数,包含Mobile和WiFi等   
static long  getUidRxBytes(int uid)  //获取某个网络UID的接受字节数  
static long  getUidTxBytes(int uid) //获取某个网络UID的发送字节数

补充:

获取字节总数转化成Text显示时,可以直接调用Formatter.formatFileSize()函数将long转化成String,函数如下:

public static String formatFileSize (Context context, long number)

 

Formats a content size to be in the form of bytes, kilobytes, megabytes, etc

Parameters
context Context to use to load the localized units
number size value to be formatted
Returns
  • formatted string with the number
第一个参数是上下文,第二个是需要转换格式的long类型的文件大小。最终返回类似 22KB、52Bytes,22MB的字符串。  

你可能感兴趣的:(android,trafficstats,实时网速,getUidRxBytes)