流量监控:
1.TrafficStats
android9以后,google逐步取消了对t_qtaguid模块的支持,可以使用TrafficStats获取
ini
synchroized long getCurrentBytes(){
long totalRxBytes = TrafficStats.getTotalRxBytes();//接受流量
long totalTxBytes = TrafficStats.getTotalTxBytes();//发送流量
if(totalRxBytes != TrafficStats.UNSUPPORTED || totalTxBytes != TrafficStats.UNSUPPORTED){
//获取设备总流量消耗
long totalBytes = totalRxBytes + totalTxBytes;
long uidRxBytes = TrafficStats.getUidRxBytes(android.os.Process.myUid());
long uidTxBytes = TrafficStats.getUidTxBytes(android.os.Process.myUid());
if(uidRxBytes != TrafficStats.UNSUPPORTED || uidTxBytes != TrafficStats.UNSUPPORTED){
return uidRxBytes+uidTxBytes;
}
return -1;
}else{
return -1;
}
}
2.NetworkStatsManager
TrafficStats可以对应用的整体流量进行查看,但是不支持根据网络接口进行区分,无法区分是WIFI还是流量。
ini
@RequiresApi(api = Build.VERSION_CODE.M)
public static long[] getNetworkUsageStats(Context context,int uid){
NetWorkStatsManger netWorkStatsManager = (NetWorkStatsManger)context.getSystemService(Context.NETRWORK_STATS_SERVICE);
NetWorkStats netWorkStats = null;
long rxBytes = 0L;
long txBytes = 0L;
try{
//结束时间为当前时间
Instant endTime = Instant.now();
//开始时间为当前时间前10min
Instant startTime = endTime.minus(Duration.ofMinutes(10));
networkStats = networkStatsManager.queryDetailsForUid(ConnectivityManager.TYPE_WIFI,
"",startTime.toEpochMill(),endTime.toEpochMill(),android.os.process.myUid());
NetWorkStats.Bucket bucket = new NetWorkStats.Bucket();
while(networkStats.hasNextBucket()){
networkStats.getNextBucket(bucket);
rxBytes += buckets.getRxBytes();
txBytes += buckets.getTxBYtes();
}
}catch(RomoteExeption e){
e.printStackTrace();
}finally{
if(networkStats != null){
networkStats.close();
}
}
return new Long[]{rxBytes,txBytes};
}
3.webview流量监控
ini
webView.setWebClient(new WebViewClient(){
@override
public void onLoadResource(WebView view,String url){
super.onLoadResource(view.url);
webViewRxBytesStart = TrafficStats.getTotalRxBytes();
webViewTxBytesStart = TrafficStats.getTotalTxBytes();
}
@override
public void onPageFinished(WebView view,String url){
super.onPageFinished(view,url);
long webViewRxBytesEnd = TrafficStats.getTotalRxBytes();
long webViewTxBytesEnd = TrafficStats.getTotalTxBytes();
long rxBytes = webViewRxBytesEnd -webViewRxBytesStart;
long txBytes = webViewTxBytesEnd -webViewTxBytesStart;
}
})
4.okhttp 流量监控
ini
public class OkHttpMoitorInterceptor implements Interceptor{
private static final String TAG = "OkHttpMoitorInterceptor";
@override
public Response intercept(Chain chain) throws IOExceptrion{
Reuqest request = chain.request();
long txBytes = request.body() != null? request.body().contentLength():0;
Response response = chain.proceed(request);
long rxBytes = response.body() != null? response.body().contentLength():0;
String url = request.url();
return response;
}
}