一、插桩
插桩需要使用到 Debug 类,并且会在 sdcard 中生成 .trace 文件,所以你必须首先保证你的应用具有写外部存储( WRITE_EXTERNAL_STORAGE )的权限。
在想要跟踪的代码逻辑开头和结尾处分别插桩:
// Starts recording a trace log with the name you provide. For example, the
// following code tells the system to start recording a .trace file to the
// device with the name “sample.trace”.
Debug.startMethodTracing(“sample”);
…
// The system begins buffering the generated trace data, until your
// application calls stopMethodTracing(), at which time it writes
// the buffered data to the output file.
Debug.stopMethodTracing();
生成的 .trace 文件会被保存在固定目录下,与 getExternalFilesDir() 返回的目录相同,即 /sdcard/Android/data/[YOUR_PACKAGE_NAME]/files 下。
请注意,如果您的应用在未更改跟踪日志名称的情况下再次调用 startMethodTracing(),则会覆盖已保存至设备的现有日志。如果希望每次运行都保存至不同的日志文件,可以使用如下代码:
// Uses the SimpleDateFormat class to create a S

本文分享了Android应用性能优化中的插桩技术,通过Debug类记录.trace文件,并探讨了使用Android Studio和traceview查看及分析这些文件的方法。此外,还介绍了CPU Profiler的使用,以无侵入的方式进行函数跟踪。

920

被折叠的 条评论
为什么被折叠?



