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;
      }
  } 
相关推荐
Sinclair1 小时前
简单几步,安卓手机秒变服务器,安装 CMS 程序
android·服务器
雮尘5 小时前
手把手带你玩转Android gRPC:一篇搞定原理、配置与客户端开发
android·前端·grpc
ktl6 小时前
Android 编译加速/优化 80%:一个文件搞定,零侵入零配置
android
alexhilton17 小时前
使用FunctionGemma进行设备端函数调用
android·kotlin·android jetpack
冬奇Lab20 小时前
InputManagerService:输入事件分发与ANR机制
android·源码阅读
张小潇1 天前
AOSP15 Input专题InputManager源码分析
android·操作系统
RdoZam1 天前
Android-封装基类Activity\Fragment,从0到1记录
android·kotlin
奥陌陌1 天前
android 打印函数调用堆栈
android
用户985120035831 天前
Compose Navigation 3 深度解析(二):基础用法
android·android jetpack
恋猫de小郭1 天前
Android 官方正式官宣 AI 支持 AppFunctions ,Android 官方 MCP 和系统级 OpenClaw 雏形
android·前端·flutter