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;
      }
  } 
相关推荐
用户69371750013841 小时前
Google 正在“收紧侧加载”:陌生 APK 安装或需等待 24 小时
android·前端
用户69371750013841 小时前
Room 3.0:这次不是升级,是重来
android·前端·google
alexhilton4 小时前
Compose中的ContentScale:终极可视化指南
android·kotlin·android jetpack
Digitally7 小时前
2026 年 8 款安卓数据擦除软件和应用对比
android
杨忆7 小时前
android 11以上 截图工具类
android
粤M温同学7 小时前
Android Studio 中安装 CodeBuddy AI助手
android·ide·android studio
阿拉斯攀登8 小时前
【RK3576 安卓 JNI/NDK 系列 08】RK3576 实战(二):JNI 调用 I2C 驱动读取传感器数据
android·安卓ndk入门·jni方法签名·java调用c++·rk3576底层开发·rk3576 i2c开发
赶路人儿9 小时前
常见的mcp配置
android·adb
符哥20089 小时前
充电桩 WiFi 局域网配网(Android/Kotlin)流程、指令及实例说明文档
android·开发语言·kotlin
没有了遇见10 小时前
Android 项目架构之<用户信息模块>
android