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;
      }
  } 
相关推荐
似霰3 小时前
HIDL Hal 开发笔记10----添加硬件访问服务(Java 层调用 HIDL)
android·framework·hal
佛系打工仔4 小时前
绘制K线第三章:拖拽功能实现
android·前端·ios
我命由我123454 小时前
Android 项目路径包含非 ASCII 字符问题:Your project path contains non-ASCII characters
android·java·java-ee·android studio·android jetpack·android-studio·android runtime
wszy18095 小时前
rn_for_openharmony_空状态与加载状态:别让用户对着白屏发呆
android·javascript·react native·react.js·harmonyos
城东米粉儿5 小时前
JobScheduler 相关笔记
android
城东米粉儿5 小时前
android 耗电优化 笔记
android
张小潇5 小时前
AOSP15的Zygote启动流程源码分析
android
毕设源码-钟学长5 小时前
【开题答辩全过程】以 基于安卓的医疗健康查询系统为例,包含答辩的问题和答案
android
归真仙人5 小时前
【UE】UMG安卓相关问题
android·ue5·游戏引擎·ue4·虚幻·unreal engine