Android流量統計TrafficStats類的使用-1

對於Android流量統計來說在2.2版中新加入了TrafficStats類可以輕鬆獲取,其實本身TrafficStats類也是讀取Linux提供的文件對象系統類型的文本進行解析。android.net.TrafficStats類中,提供了多種靜態方法,可以直接調用獲取,返回類型均爲 long型,如果返回等於-1代表 UNSUPPORTED 當前設備不支持統計。

Java代碼  收藏代碼
  1. static long  getMobileRxBytes()  //獲取通過Mobile連接收到的字節總數,不包含WiFi  
  2. static long  getMobileRxPackets()  //獲取Mobile連接收到的數據包總數  
  3. static long  getMobileTxBytes()  //Mobile發送的總字節數  
  4. static long  getMobileTxPackets()  //Mobile發送的總數據包數  
  5. static long  getTotalRxBytes()  //獲取總的接受字節數,包含Mobile和WiFi等  
  6. static long  getTotalRxPackets()  //總的接受數據包數,包含Mobile和WiFi等  
  7. static long  getTotalTxBytes()  //總的發送字節數,包含Mobile和WiFi等  
  8. static long  getTotalTxPackets()  //發送的總數據包數,包含Mobile和WiFi等   
  9. static long  getUidRxBytes(int uid)  //獲取某個網絡UID的接受字節數  
  10. static long  getUidTxBytes(int uid) //獲取某個網絡UID的發送字節數   
總接受流量TrafficStats.getTotalRxBytes(),
總髮送流量TrafficStats.getTotalTxBytes());
不包含WIFI的手機GPRS接收量TrafficStats.getMobileRxBytes());
不包含Wifi的手機GPRS發送量TrafficStats.getMobileTxBytes());

某一個進程的總接收量TrafficStats.getUidRxBytes(Uid));
某一個進程的總髮送量TrafficStats.getUidTxBytes(Uid));

這些都是從第一次啓動程序到最後一次啓動的統計量。並不是這篇文章裏所說的“從本次開機到本次關機的統計量”!

用法舉例,注意這裏得到的單位都是"KB"
Java代碼  收藏代碼
  1. public long getTotalRxBytes(){  //獲取總的接受字節數,包含Mobile和WiFi等  
  2.         return TrafficStats.getTotalRxBytes()==TrafficStats.UNSUPPORTED?0:(TrafficStats.getTotalRxBytes()/1024);  
  3.     }  
  4.     public long getTotalTxBytes(){  //總的發送字節數,包含Mobile和WiFi等  
  5.         return TrafficStats.getTotalTxBytes()==TrafficStats.UNSUPPORTED?0:(TrafficStats.getTotalTxBytes()/1024);  
  6.     }  
  7.     public long getMobileRxBytes(){  //獲取通過Mobile連接收到的字節總數,不包含WiFi  
  8.         return TrafficStats.getMobileRxBytes()==TrafficStats.UNSUPPORTED?0:(TrafficStats.getMobileRxBytes()/1024);  
  9.     }  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章