Android流量監控
1、TrafficStats類的使用
以下結論,是自己真機實測的結果,與自己在網上看到的不同,大家可自測驗證。
(1)getMobile...方法,獲取Gprs/3G流量
(2)getTotal...方法,獲取Gprs/3G+Wifi的流量
以上兩類方法統計的都是,從打開網絡開始,到關閉網絡,這一段時間內使用的流量。例如:10點打開,11點關閉,那么getMobileRxBytes方法,回返的是這段時間內Gprs/3G接受到的字節數。
(3)getUid...方法,獲取某個網絡UID的流量。這類方法,返回的是,從開機到關機,某個網絡UID(我理解就是某個應用,如果不對,請在評論中指正)使用的Gprs/3G+Wifi的流量
2、getUid...方法的使用
List<PackageInfo> packinfos = pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_PERMISSIONS);
for (PackageInfo info : packinfos) {
String[] premissions = info.requestedPermissions;
if (premissions != null && premissions.length > 0) {
for (String premission : premissions) {
if ("android.permission.INTERNET".equals(premission)) {
// System.out.println(info.packageName+"訪問網絡");
int uid = info.applicationInfo.uid;
long rx = TrafficStats.getUidRxBytes(uid);
long tx = TrafficStats.getUidTxBytes(uid);
if (rx < 0 || tx < 0) {
System.out.println(info.packageName + "沒有產生流量");
} else {
System.out.println(info.packageName + "的流量信息:");
System.out.println("下載的流量" + Formatter.formatFileSize(this, rx));
System.out.println("上傳的流量" + Formatter.formatFileSize(this, tx));
}
}
}
System.out.println("---------");
}
} 3、獲取流量信息的Service類
(1)因為兩個廣播都需要動態注冊,所以寫成了Service
(2)getMobile...和getTotal...方法獲取的都是從打開網絡開始,到關閉網絡,這一段時間內使用的流量。
因此要在網絡正在關閉時獲取的就是這段時間的流量,WifiManager.WIFI_STATE_DISABLING表示的就是這個狀態
(3)Gprs/3G貌似沒有類似的狀態,可以被監控到,只有,State.CONNECTED和State.DISCONNECTED。但是處于State.DISCONNECTED這個狀態時,getMobile...方法獲取到的值就都是0了
所有,我不得不在State.CONNECTED這個狀態開始時,開啟線程用于獲取Gprs/3G的流量,直到我獲取的到數據為0時,保存上一次的數據。
package forrest.forassist.service;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.TrafficStats;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.text.format.Formatter;
import android.util.Log;
import forrest.forassist.db.MySQLiteDatabase;
import forrest.forassist.utils.Util;
public class TrafficService extends Service {
private TrafficReceiver tReceiver;
private WifiManager wifiManager;
private ConnectivityManager cManager;
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
// WifiManager,ConnectivityManager
wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
cManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
// 注冊TrafficReceiver
tReceiver = new TrafficReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(tReceiver, filter);
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
private class TrafficReceiver extends BroadcastReceiver {
private String action = "";
private static final String TAG = "TrafficReceiver";
long mobileRx;
long mobileTx;
public void onReceive(Context context, Intent intent) {
action = intent.getAction();
if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_DISABLING) {
Log.i(TAG, "WIFI_STATE_DISABLING");
long wifiDown = TrafficStats.getTotalRxBytes() - TrafficStats.getMobileRxBytes();
long wifiUp = TrafficStats.getTotalTxBytes() - TrafficStats.getMobileTxBytes();
MySQLiteDatabase sqLite = new MySQLiteDatabase(context); // 打開數據庫
sqLite.insertWifi(Util.todayDate, wifiDown, wifiUp);
sqLite.closeDB();
Log.i(TAG, "wifi下載流量" + Formatter.formatFileSize(context, wifiDown));
Log.i(TAG, "wifi上傳流量" + Formatter.formatFileSize(context, wifiUp));
}
} else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Log.i(TAG, "CONNECTIVITY_ACTION");
NetworkInfo networkInfo = cManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
State state = networkInfo.getState();
if (state == State.CONNECTED) {
Log.i(TAG, "State.CONNECTED");
// 開始不斷獲取最近的流量信息,值為0時,跳過
new Thread() {
public void run() {
long mobileRxType = TrafficStats.getMobileRxBytes();
long mobileTxType = TrafficStats.getMobileTxBytes();
if (mobileRxType + mobileTxType != 0) {
try {
mobileRx = mobileRxType;
mobileTx = mobileTxType;
Log.i(TAG, "mobileRx:" + mobileRx);
Log.i(TAG, "mobileTx:" + mobileTx);
Thread.sleep(1000);
run();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
// 寫入數據庫
Log.i(TAG, "寫入數據庫");
MySQLiteDatabase sqLite = new MySQLiteDatabase(TrafficService.this);
sqLite.insertGprs(Util.todayDate, mobileRx, mobileTx);
sqLite.closeDB();
}
};
}.start();
}
}
}
}
public void onDestroy() {
unregisterReceiver(tReceiver);
super.onDestroy();
}
}
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!