android 流量优化笔记

流量监控:

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;
      }
  } 
相关推荐
STCNXPARM11 小时前
Android camera之硬件架构
android·硬件架构·camera
2501_9445255413 小时前
Flutter for OpenHarmony 个人理财管理App实战 - 支出分析页面
android·开发语言·前端·javascript·flutter
松☆14 小时前
Dart 核心语法精讲:从空安全到流程控制(3)
android·java·开发语言
_李小白16 小时前
【Android 美颜相机】第二十三天:GPUImageDarkenBlendFilter(变暗混合滤镜)
android·数码相机
小天源18 小时前
银河麒麟 V10(x86_64)离线安装 MySQL 8.0
android·mysql·adb·麒麟v10
2501_9159214318 小时前
傻瓜式 HTTPS 抓包,简单抓取iOS设备数据
android·网络协议·ios·小程序·https·uni-app·iphone
csj5020 小时前
安卓基础之《(20)—高级控件(2)列表类视图》
android
JMchen12320 小时前
Android计算摄影实战:多帧合成、HDR+与夜景算法深度剖析
android·经验分享·数码相机·算法·移动开发·android-studio
恋猫de小郭21 小时前
Flutter 在 Android 出现随机字体裁剪?其实是图层合并时的边界计算问题
android·flutter·ios
2501_9159184121 小时前
把 iOS 性能监控融入日常开发与测试流程的做法
android·ios·小程序·https·uni-app·iphone·webview