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;
      }
  } 
相关推荐
lpruoyu1 小时前
【Android第一行代码学习笔记】Android架构_四大组件_权限_持久化_通知_异步_服务
android·笔记·学习
独自破碎E2 小时前
【BISHI15】小红的夹吃棋
android·java·开发语言
李堇5 小时前
android滚动列表VerticalRollingTextView
android·java
lxysbly6 小时前
n64模拟器安卓版带金手指2026
android
游戏开发爱好者89 小时前
日常开发与测试的 App 测试方法、查看设备状态、实时日志、应用数据
android·ios·小程序·https·uni-app·iphone·webview
王码码20359 小时前
Flutter for OpenHarmony 实战之基础组件:第三十一篇 Chip 系列组件 — 灵活的标签化交互
android·flutter·交互·harmonyos
黑码哥10 小时前
ViewHolder设计模式深度剖析:iOS开发者掌握Android列表性能优化的实战指南
android·ios·性能优化·跨平台开发·viewholder
亓才孓10 小时前
[JDBC]元数据
android
独行soc10 小时前
2026年渗透测试面试题总结-17(题目+回答)
android·网络·安全·web安全·渗透测试·安全狮
金融RPA机器人丨实在智能10 小时前
Android Studio开发App项目进入AI深水区:实在智能Agent引领无代码交互革命
android·人工智能·ai·android studio