Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 統計 WiFi/2G/3G/4G 流量的實作

編輯:關於 Android 程式設計

需求:統計 WiFi、2G、3G、4G 各自的流量使用情況。

要點分析

一、如何判斷 2G/3G/4G:系統源碼 TelephonyManager 類別提供了相關方法,只是被隱藏了,可參考源碼。

二、如何統計:Android 2.2 之後提供了 TrafficStats 類別用於流量統計,這裡主要用到:

static long getTotalRxBytes():獲取總的接收位元組數,包含 Mobile 與 WiFi 等;
static long getTotalTxBytes():總的發送位元組數,包含 Mobile 與 WiFi 等。

三、注意事項:

1、android.net.conn.CONNECTIVITY_CHANGE 廣播會在手機網路類型切換時由系統發送;
2、TrafficStats.getTotalRxBytes() 與 getTotalTxBytes() 取得的值是從開機開始累計的。

實作步驟

1、建立 TrafficData 資料表,欄位包含 trafficData(該網路使用了多少流量)、subtype(網路類型)、starttime(開始時間)、endtime(結束時間)。

2、建立 SharedPreferences,記錄 lastSystemTraffic(上次系統的流量大小)、subtype(網路類型)、startTime。

3、註冊 DataTrafficReceiver,監聽 CONNECTIVITY_CHANGE 廣播與關機廣播。當網路變化時,取得 currentTraffic = TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes(),並讀取 SP 中保存的 lastSystemTraffic,兩者相減即為本次網路使用流量 durationTraffic,將其存入資料表並更新 SP 中的值。

4、手機重啟時,重複步驟 3 並清空 SP 中的值。

透過這種「累計值差分」的方式,即可在不同網路類型切換時,精確統計各類網路的流量消耗。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved