一、插桩
插桩需要使用到 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 String with
// the current date and time.
SimpleDateFormat date =
new SimpleDateFormat(“dd_MM_yyyy_hh_mm_ss”);
String logDate = date.format(new Date());
// Applies the date and time to the name of the trace log.
Debug.startMethodTracing(
“sample-” + logDate);
如果系统在您调用 stopMethodTracing() 之前达到最大缓冲值,则会停止跟踪并向管理中心发送通知。 开始和停止跟踪的函数在您的整个应用流程内均有效。 也就是说