如何擷取設定檔

本頁面說明如何使用 ProfilingManager API 記錄系統追蹤記錄。

新增依附元件

如要獲得最佳 ProfilingManager API 體驗,請將下列 Jetpack 程式庫新增至 build.gradle.kts 檔案。

Kotlin

   dependencies {
       implementation("androidx.tracing:tracing:1.3.0")
       implementation("androidx.core:core:1.16.0")
   }
   

Groovy

   dependencies {
       implementation 'androidx.tracing:tracing:1.3.0'
       implementation 'androidx.core:core:1.16.0'
   }
   

錄製系統追蹤記錄

新增必要依附元件後,請使用下列程式碼記錄系統追蹤記錄。這個範例顯示 Activity 中的基本設定,可啟動及管理剖析工作階段。

Kotlin

@RequiresApi(Build.VERSION_CODES.VANILLA_ICE_CREAM)
fun sampleRecordSystemTrace() {
    val mainExecutor: Executor =
        Dispatchers.IO.asExecutor() // Your choice of executor for the callback to occur on.
    val resultCallback = Consumer<ProfilingResult> { profilingResult ->
        if (profilingResult.errorCode == ProfilingResult.ERROR_NONE) {
            Log.d(
                "ProfileTest",
                "Received profiling result file=" + profilingResult.resultFilePath
            )
        } else {
            Log.e(
                "ProfileTest",
                "Profiling failed errorcode=" + profilingResult.errorCode + " errormsg=" + profilingResult.errorMessage
            )
        }
    }
    val stopSignal = CancellationSignal()

    val requestBuilder = SystemTraceRequestBuilder()
    requestBuilder.setCancellationSignal(stopSignal)
    requestBuilder.setTag("FOO") // Caller supplied tag for identification
    requestBuilder.setDurationMs(60000)
    requestBuilder.setBufferFillPolicy(BufferFillPolicy.RING_BUFFER)
    requestBuilder.setBufferSizeKb(20971520)
    requestProfiling(applicationContext, requestBuilder.build(), mainExecutor, resultCallback)

    // Wait some time for profiling to start.

    Trace.beginSection("MyApp:HeavyOperation")
    heavyOperation()
    Trace.endSection()

    // Once the interesting code section is profiled, stop profile
    stopSignal.cancel()
}

fun heavyOperation() {
    // Computations you want to profile
}

Java

void heavyOperation() {
  // Computations you want to profile
}

void sampleRecordSystemTrace() {
  Executor mainExecutor = Executors.newSingleThreadExecutor();
  Consumer<ProfilingResult> resultCallback =
      new Consumer<ProfilingResult>() {
        @Override
        public void accept(ProfilingResult profilingResult) {
          if (profilingResult.getErrorCode() == ProfilingResult.ERROR_NONE) {
            Log.d(
                "ProfileTest",
                "Received profiling result file=" + profilingResult.getResultFilePath());
          } else {
            Log.e(
                "ProfileTest",
                "Profiling failed errorcode="

                    + profilingResult.getErrorCode()
                    + " errormsg="
                    + profilingResult.getErrorMessage());
          }
        }
      };
  CancellationSignal stopSignal = new CancellationSignal();

  SystemTraceRequestBuilder requestBuilder = new SystemTraceRequestBuilder();
  requestBuilder.setCancellationSignal(stopSignal);
  requestBuilder.setTag("FOO");
  requestBuilder.setDurationMs(60000);
  requestBuilder.setBufferFillPolicy(BufferFillPolicy.RING_BUFFER);
  requestBuilder.setBufferSizeKb(20971520);
  Profiling.requestProfiling(getApplicationContext(), requestBuilder.build(), mainExecutor,
      resultCallback);

  // Wait some time for profiling to start.

  Trace.beginSection("MyApp:HeavyOperation");
  heavyOperation();
  Trace.endSection();

  // Once the interesting code section is profiled, stop profile
  stopSignal.cancel();
}

程式碼範例會執行下列步驟,設定及管理剖析工作階段:

  1. 設定執行器。建立 Executor,定義接收剖析結果的執行緒。剖析作業會在背景執行。如果您稍後要在回呼中新增更多處理作業,使用非 UI 執行緒執行器有助於避免發生應用程式無回應 (ANR) 錯誤。

  2. 處理剖析結果。建立 Consumer<ProfilingResult> 物件。 系統會使用這個物件,將 ProfilingManager 的剖析結果傳回應用程式。

  3. 建立剖析要求。建立 SystemTraceRequestBuilder 來設定剖析工作階段。這個建構工具可讓您自訂 ProfilingManager 追蹤設定。自訂建構工具是選用步驟,如未自訂,系統會使用預設設定。

    • 定義標記。使用 setTag() 將標記新增至追蹤名稱。這個標記有助於識別追蹤記錄。
    • 選用:設定時間長度。使用 setDurationMs() 指定要分析的毫秒數。舉例來說,60000 會設定 60 秒的追蹤記錄。如果未在指定時間內觸發 CancellationSignal,追蹤作業會在時間到期後自動結束。
    • 選擇緩衝區政策。使用 setBufferFillPolicy() 定義追蹤資料的儲存方式。BufferFillPolicy.RING_BUFFER 表示緩衝區已滿時,新資料會覆寫最舊的資料,持續記錄近期活動。
    • 設定緩衝區大小。使用 setBufferSizeKb() 指定追蹤記錄的緩衝區大小,藉此控制輸出追蹤記錄檔案的大小。
  4. 選用:管理工作階段生命週期。建立 CancellationSignal。 您可以隨時停止剖析工作階段,精確控制工作階段長度。

  5. 開始檢測並接收結果。撥打 requestProfiling() 時,ProfilingManager 會在背景啟動剖析工作階段。完成剖析後,系統會將 ProfilingResult 傳送至您的 resultCallback#accept 方法。如果剖析作業順利完成,ProfilingResult 會透過 ProfilingResult#getResultFilePath 提供追蹤記錄在裝置上的儲存路徑。您可以透過程式輔助取得這個檔案,也可以在電腦上執行 adb pull <trace_path> 進行本機剖析。

  6. 新增自訂追蹤點。您可以在應用程式的程式碼中新增自訂追蹤點。在先前的程式碼範例中,系統會使用 Trace.beginSection()Trace.endSection() 新增名為 MyApp:HeavyOperation 的追蹤記錄切片。這個自訂切片會顯示在產生的設定檔中,醒目顯示應用程式內的特定作業。