檢測應用程式以產生追蹤記錄
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
若要產生應用程式執行作業的方法追蹤記錄,您可以使用 Debug
類別檢測應用程式。以這種方式檢測應用程式,可讓您更精確地控制裝置開始及停止記錄追蹤資訊的時間。裝置也會使用您指定的名稱儲存追蹤記錄,方便您之後識別每個記錄檔。接下來,您可以使用 Android Studio CPU 分析器查看每個追蹤記錄。
您也可以在 CPU 分析器中啟動及停止追蹤,而不必檢測應用程式的程式碼。
開始產生追蹤記錄之前,請先確認您的應用程式已新增邏輯,可將追蹤記錄儲存至應用程式專用的目錄。
檢測應用程式
若要建立追蹤記錄,請在系統開始記錄追蹤資料的位置呼叫 startMethodTracing()
。
在呼叫中,您可以為 .trace
檔案指定名稱,讓系統將檔案儲存到套件專屬目錄中,以便用於目標裝置上的永久應用程式資料。此為由 getExternalFilesDir()
傳回的相同目錄,且位於大多數裝置的 ~/sdcard/
目錄中。檔案含有二進位方法追蹤記錄資料,以及包含執行緒和方法名稱的對應資料表。若要停止追蹤,請呼叫 stopMethodTracing()
。
下列範例會開始及停止記錄名為 sample.trace
的追蹤記錄:
Kotlin
// 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 <code><a href="/reference/android/os/Debug.html#stopMethodTracing()">stopMethodTracing()</a></code>, at which time it writes
// the buffered data to the output file.
Debug.stopMethodTracing()
Java
// 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 <code><a href="/reference/android/os/Debug.html#stopMethodTracing()">stopMethodTracing()</a></code>, at which time it writes
// the buffered data to the output file.
Debug.stopMethodTracing();
請注意,如果您的應用程式再次呼叫 startMethodTracing()
,而未變更追蹤記錄名稱,則會覆寫儲存在裝置上的現有記錄。若要瞭解如何動態變更每個追蹤記錄的名稱,請參閱「儲存多個記錄檔」一節。
如果系統在您呼叫 stopMethodTracing()
前達到緩衝區空間上限,系統會停止追蹤,並傳送通知至主控台。開始和停止追蹤記錄的方法適用於整個應用程式程序。也就是說,您可以在活動的 onCreate(Bundle)
方法中呼叫 startMethodTracing()
,並在該活動的 onDestroy()
方法中呼叫 stopMethodTracing()
。
請注意,啟用剖析功能時,應用程式執行速度會變慢。也就是說,您不應使用剖析資料來判斷絕對時間 (例如「方法 foo()
需要 2.5 秒才能執行」)。只有在與先前的追蹤記錄進行比較時,追蹤記錄中的時間資訊才有用,以便查看近期的變更是否加快或減緩應用程式的運作速度。
部署至搭載 Android 5.0 (API 級別 21) 以上版本的裝置時,您可以使用樣本式剖析功能,以降低對執行階段效能的影響。若要啟用樣本剖析,請以指定的取樣間隔呼叫 startMethodTracingSampling()
(而非呼叫 startMethodTracing()
)。系統會定期收集樣本,直到應用程式呼叫 stopMethodTracing()
為止。
儲存多個記錄檔
如果應用程式多次啟動並停止方法追蹤記錄,卻沒有指定追蹤記錄的新名稱,裝置就會用新的記錄覆寫舊的追蹤記錄;也就是說,系統只會保留最新的追蹤記錄。若要將多個追蹤記錄儲存到您的裝置中,請在應用程式呼叫 startMethodTracing()
時動態重新命名追蹤記錄。以下範例使用 SimpleDateFormat
類別,在每個追蹤記錄命名時加入目前的日期和時間:
Kotlin
// Uses the <code><a href="/reference/java/text/SimpleDateFormat.html">SimpleDateFormat</a></code> class to create a String with
// the current date and time.
val dateFormat: DateFormat = SimpleDateFormat("dd_MM_yyyy_hh_mm_ss", Locale.getDefault())
val logDate: String = dateFormat.format(Date())
// Applies the date and time to the name of the trace log.
Debug.startMethodTracing("sample-$logDate")
Java
// Uses the <code><a href="/reference/java/text/SimpleDateFormat.html">SimpleDateFormat</a></code> class to create a String with
// the current date and time.
SimpleDateFormat dateFormat =
new SimpleDateFormat("dd_MM_yyyy_hh_mm_ss", Locale.getDefault());
String logDate = dateFormat.format(new Date());
// Applies the date and time to the name of the trace log.
Debug.startMethodTracing(
"sample-" + logDate);
存取裝置上的追蹤記錄
系統在裝置上建立追蹤記錄後,您可以透過下列其中一種方式存取檔案:
使用 Device Explorer。如要開啟 Device Explorer,請依序點選「View」>「Tool Windows」>「Device Explorer」,或者按一下工具視窗列中的「Device Explorer」按鈕
。如圖 1 所示,只要前往應用程式的套件專屬目錄,即可找到 .trace
檔案。
圖 1. 使用 Device Explorer 找到追蹤記錄。
使用 adb pull
指令,將檔案複製到本機電腦。下列指令會將名為 sample.trace
的追蹤記錄從裝置複製到本機電腦的 ~/Documents/trace-logs/
目錄。
adb pull path-on-device/sample.trace ~/Documents/trace-logs/
接下來,您可以使用 CPU 分析器匯入追蹤記錄檔。
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。Java 與 OpenJDK 是 Oracle 和/或其關係企業的商標或註冊商標。
上次更新時間:2025-07-27 (世界標準時間)。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-07-27 (世界標準時間)。"],[],[],null,["# Generate Trace Logs by Instrumenting Your App\n\nTo generate a method trace of your app's execution, you can instrument your app\nusing the [Debug](/reference/android/os/Debug)\nclass. Instrumenting your app this way gives you more control over exactly when\nthe device starts and stops recording tracing information. The device also saves\nyour trace logs using the names you specify, so you can easily identify each log\nlater. You can then view each trace log using the Android Studio\n[CPU Profiler](/studio/profile/cpu-profiler).\n\nYou can also\n[start and stop tracing in the CPU Profiler](/studio/profile/cpu-profiler#method_traces)\nwithout instrumenting your app's code.\n\nBefore you start generating trace logs, make sure your app has added logic to\nsave trace logs to its [app-specific\ndirectory](/training/data-storage/app-specific).\n\nInstrument your app\n-------------------\n\nTo create trace logs, call [startMethodTracing()](/reference/android/os/Debug#startMethodTracing())\nwhere you want the system to start logging tracing data.\n\nIn the call, you can specify the name for the\n`.trace` file, and the system saves it to a package-specific\ndirectory that's intended for persistent app data on the target device---this is\nthe same directory that is returned by\n[getExternalFilesDir()](/reference/android/content/Context#getExternalFilesDir(java.lang.String))\nand is located in the `~/sdcard/` directory on most devices.\nThis file contains the binary method trace data and a mapping table with thread\nand method names. To stop tracing, call\n[stopMethodTracing()](/reference/android/os/Debug#stopMethodTracing()).\n\nThe following sample starts and stops recording a trace log with the name\n`sample.trace`: \n\n### Kotlin\n\n```kotlin\n// Starts recording a trace log with the name you provide. For example, the\n// following code tells the system to start recording a .trace file to the\n// device with the name \"sample.trace\".\nDebug.startMethodTracing(\"sample\")\n\n// The system begins buffering the generated trace data, until your\n// application calls \u003ccode\u003e\u003ca href=\"/reference/android/os/Debug.html#stopMethodTracing()\"\u003estopMethodTracing()\u003c/a\u003e\u003c/code\u003e, at which time it writes\n// the buffered data to the output file.\nDebug.stopMethodTracing()\n```\n\n### Java\n\n```java\n// Starts recording a trace log with the name you provide. For example, the\n// following code tells the system to start recording a .trace file to the\n// device with the name \"sample.trace\".\nDebug.startMethodTracing(\"sample\");\n...\n// The system begins buffering the generated trace data, until your\n// application calls \u003ccode\u003e\u003ca href=\"/reference/android/os/Debug.html#stopMethodTracing()\"\u003estopMethodTracing()\u003c/a\u003e\u003c/code\u003e, at which time it writes\n// the buffered data to the output file.\nDebug.stopMethodTracing();\n```\n\nNote that if your app calls the\n[startMethodTracing()](/reference/android/os/Debug#startMethodTracing())\nagain without changing the name of the trace log, it overwrites the existing log\nsaved to the device. To learn how to dynamically change the name of each trace\nlog, go to the section about [saving multiple logs](#save_multiple_logs).\n\nIf the system reaches the maximum buffer size before you call\n[stopMethodTracing()](/reference/android/os/Debug#stopMethodTracing()),\nthe system stops tracing and sends a notification to the console.\nThe methods that start and stop traces work across your entire app process. That\nis, you could call\n[startMethodTracing()](/reference/android/os/Debug#startMethodTracing())\nin your activity's\n[onCreate(Bundle)](/reference/android/app/Activity#onCreate(android.os.Bundle))\nmethod, and call [stopMethodTracing()](/reference/android/os/Debug#stopMethodTracing())\nin that activity's [onDestroy()](/reference/android/app/Activity#onDestroy())\nmethod.\n\nNote that your app runs more slowly when profiling is enabled. That is, you\nshouldn't use the profiling data to determine absolute timings (such as, \"method\n`foo()` takes 2.5 seconds to run\"). The timing information in the trace logs are\nuseful only when comparing it to previous trace logs, so you can see if recent\nchanges make your app faster or slower.\n\nWhen deploying to devices running Android 5.0 (API level 21) and higher, you can\nuse sample-based profiling to profile with less runtime performance impact. To\nenable sample profiling, call\n[startMethodTracingSampling()](/reference/android/os/Debug#startMethodTracingSampling(java.lang.String, int, int))\n(instead of calling `startMethodTracing()`) with a specified sampling\ninterval. The system gathers samples periodically until your app calls\n[stopMethodTracing()](/reference/android/os/Debug#stopMethodTracing()).\n\n### Save multiple logs\n\nIf your app starts and stops a method trace multiple times without specifying a\nnew name for the trace log, the device overwrites the older trace log with the\nnew one---that is, it only keeps the most recent trace log. To save multiple\ntrace logs to your device, dynamically rename the trace log each time your app\ncalls [startMethodTracing()](/reference/android/os/Debug#startMethodTracing()).\nThe sample below uses the [SimpleDateFormat](/reference/java/text/SimpleDateFormat)\nclass to include the current date and time when naming each trace log: \n\n### Kotlin\n\n```kotlin\n// Uses the \u003ccode\u003e\u003ca href=\"/reference/java/text/SimpleDateFormat.html\"\u003eSimpleDateFormat\u003c/a\u003e\u003c/code\u003e class to create a String with\n// the current date and time.\nval dateFormat: DateFormat = SimpleDateFormat(\"dd_MM_yyyy_hh_mm_ss\", Locale.getDefault())\nval logDate: String = dateFormat.format(Date())\n// Applies the date and time to the name of the trace log.\nDebug.startMethodTracing(\"sample-$logDate\")\n```\n\n### Java\n\n```java\n// Uses the \u003ccode\u003e\u003ca href=\"/reference/java/text/SimpleDateFormat.html\"\u003eSimpleDateFormat\u003c/a\u003e\u003c/code\u003e class to create a String with\n// the current date and time.\nSimpleDateFormat dateFormat =\n new SimpleDateFormat(\"dd_MM_yyyy_hh_mm_ss\", Locale.getDefault());\nString logDate = dateFormat.format(new Date());\n// Applies the date and time to the name of the trace log.\nDebug.startMethodTracing(\n \"sample-\" + logDate);\n```\n\nAccess trace logs on the device\n-------------------------------\n\nAfter the system creates the trace log on your device, you can access the file\nin one of the following ways:\n\n- [Use the Device Explorer](/studio/debug/device-file-explorer).\n To open the Device Explorer, click\n **View \\\u003e Tool Windows \\\u003e Device Explorer** (or click the\n **Device Explorer**\n button in the tool window bar). As shown in figure 1\n you can locate the `.trace` files by navigating to your app's\n package-specific directory.\n\n\n **Figure 1.** Locating the trace logs using the Device Explorer.\n\n \u003cbr /\u003e\n\n- Copy the file to your local machine using the `adb pull` command.\n The command below copies a trace log named `sample.trace` from the device to\n the `~/Documents/trace-logs/` directory of your local machine.\n\n ```\n adb pull path-on-device/sample.trace ~/Documents/trace-logs/\n ```\n\n \u003cbr /\u003e\n\nYou can then\n[import the trace file](/studio/profile/import-traces) with the CPU Profiler."]]