美文网首页Android性能优化Android性能优化Android知识
四、Android性能优化之性能优化工具

四、Android性能优化之性能优化工具

作者: 香沙小熊 | 来源:发表于2017-08-31 11:42 被阅读137次

    性能优化的帮助工具:
    MAT,
    Memory Monitor(属于AndroidMonitor中一个模块),
    HeapTool(查看堆信息),
    Allaction Tracking,
    LeakCanary
    Lint工具

    1.Allaction Tracking

    (1)追踪


    Allaction Tracking

    在内存图中点击途中箭头的部分,启动追踪,再次点击就是停止追踪,随后自动生成一个alloc结尾的文件,这个文件就记录了这次追踪到的所有数据,然后会在右上角打开一个窗口。展示和第一种方式有点区别,各有所长,他有两种展现方式。

    (2)分类我们的内存分配


    生成的alloc文件

    红框中

    Group by Method:用方法来分类我们的内存分配,默认会以Group by Method来组织
    Group by Allocator:用内存分配器来分类我们的内存分配

    我们用 Group by Allocator的方式来查看一下。

    可以看到我们自己包中,每一个类的内存分配次数和分配的大小。如果我们想看内存分配的实际在源码中发生的地方,可以选择需要跳转的对象,点击该按钮就能发现我们的源码。

    (3)查看统计图

    想看某个图层详细内存分配,则双击速表左键进入下一图层


    内存分配情况

    通过[Layout方式查看更直观

    Layout方式

    特别感谢
    LooperJing

    2.LeakCanary
    (1)配置

    Getting started
    
    In your build.gradle:
    
     dependencies {
       debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.2'
       releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.2'
     }
    In your Application class:
    
    public class ExampleApplication extends Application {
    
      @Override public void onCreate() {
        super.onCreate();
        if (LeakCanary.isInAnalyzerProcess(this)) {
          // This process is dedicated to LeakCanary for heap analysis.
          // You should not init your app in this process.
          return;
        }
        LeakCanary.install(this);
        // Normal app init code...
      }
    }
    

    (2)制造一个单例内存泄漏的点

    public class CommonUtils {
    
        private static CommonUtils instance;
    
        private Context context;
    
        private CommonUtils(Context context) {
            this.context = context;
        }
    
        public static CommonUtils getInstance(Context context) {
    
            if (instance == null) {
                instance = new CommonUtils(context);
            }
            return instance;
        }
    }
    
     protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            CommonUtils commonUtils = CommonUtils.getInstance(this);
    
        }
    

    (3)LeakCanary 发出内存泄漏通知



    (4)LeakCanary 分析
    LeakCanary 本质上还是用命令控制生成hprof文件分析检查内存泄漏。

    3.Lint分析工具

    Android Studio很方便,很好用,你可以试试点击AS菜单栏上面的Analyze选项,然后点击Inspection Scope,然后选择你需要检测的范围(比如整个项目),然后AS会自动弹出下图所示的面板


    lint分析展示面板 可能出现内存泄漏的类
    检测资源文件是否有没有用到的资源。
    检测常见内存泄露
    安全问题SDK版本安全问题
    是否有费的代码没有用到
    代码的规范---甚至驼峰命名法也会检测
    自动生成的罗列出来
    没用的导包
    可能的bug

    相关文章

      网友评论

        本文标题:四、Android性能优化之性能优化工具

        本文链接:https://www.haomeiwen.com/subject/sqvxjxtx.html