本页介绍了如何使用 ProfilingManager API 记录系统轨迹。
ProfilingManager 还可以记录其他类型的分析。此流程与记录系统轨迹类似,但每种类型使用不同的构建器。支持的配置文件及其构建器如下:
系统轨迹:使用
SystemTraceRequestBuilder记录,有助于进行延迟时间分析和常规性能调试。堆转储:使用
JavaHeapDumpRequestBuilder记录,有助于检测和优化内存泄漏。堆性能分析文件:使用
HeapProfileRequestBuilder记录,有助于优化内存。调用堆栈配置文件:使用
StackSamplingRequestBuilder记录,有助于了解代码执行情况和进行延迟时间分析。
添加依赖项
为了获得最佳的 ProfilingManager API 使用体验,请将以下 Jetpack 库添加到您的 build.gradle.kts 文件中。
Kotlin
dependencies { implementation("androidx.tracing:tracing-ktx:2.0.2") implementation("androidx.core:core:1.19.0") }
Groovy
dependencies { implementation 'androidx.tracing:tracing:2.0.2' implementation 'androidx.core:core:1.19.0' }
录制系统跟踪记录
添加所需的依赖项后,使用以下代码记录系统轨迹。此示例展示了如何从可组合项启动分析会话,同时安全地在主线程之外管理繁重的操作。
Kotlin
@RequiresApi(Build.VERSION_CODES.VANILLA_ICE_CREAM)
@Composable
fun ProfiledScreen(modifier: Modifier = Modifier) {
// Use the application context: requestProfiling resolves the ProfilingManager
// system service from it, so there's no reason to hand it a short-lived Activity.
val appContext = LocalContext.current.applicationContext
val scope = rememberCoroutineScope()
Button(
onClick = {
// Run the orchestration off the main thread. Profiling a heavy operation
// on the UI thread would freeze the UI (ANR) and distort the very metrics
// you're trying to capture.
//
// Note: this scope is tied to composition. If the user leaves this screen
// mid-session, the coroutine is cancelled and stopSignal.cancel() might not
// run, but setDurationMs() acts as a safety net and ends the trace.
scope.launch(Dispatchers.Default) {
val callbackExecutor = Dispatchers.IO.asExecutor()
val resultCallback = Consumer<ProfilingResult> { profilingResult ->
if (profilingResult.errorCode == ProfilingResult.ERROR_NONE) {
Log.d("ProfileTest", "Result file: ${profilingResult.resultFilePath}")
} else {
// errorMessage explains the failure (e.g., rate limiting); keep it.
Log.e(
"ProfileTest",
"Profiling failed errorCode=${profilingResult.errorCode} " +
"errorMessage=${profilingResult.errorMessage}"
)
}
}
val stopSignal = CancellationSignal()
val requestBuilder = SystemTraceRequestBuilder().apply {
setCancellationSignal(stopSignal)
setTag("FOO") // Caller-supplied tag for identification.
setDurationMs(60000) // Hard cap: ends the session if cancel() never fires.
setBufferFillPolicy(BufferFillPolicy.RING_BUFFER)
setBufferSizeKb(32768)
}
// 1. Start the session. This is asynchronous system IPC. The tracing
// engine takes a moment to start and allocate buffers.
requestProfiling(appContext, requestBuilder.build(), callbackExecutor, resultCallback)
// 2. The API exposes no "profiling started" signal, so pad with a short,
// best-effort delay before running the code you care about. This is
// approximate. Increase it on slower or heavily loaded devices.
delay(STARTUP_PADDING_MS)
// 3. The session is already recording every thread in your app. This slice
// doesn't scope what's captured. It just labels this region of the
// timeline so heavyOperation() is easier to find. trace { } closes the
// section even if the block throws.
trace("MyApp:HeavyOperation") {
heavyOperation()
}
// 4. Stop recording. Until this fires or the setDurationMs() cap is
// reached (whichever comes first), the session keeps capturing app-wide
// activity.
stopSignal.cancel()
}
}
) {
Text("Run & Profile Heavy Operation")
}
}
// Best-effort wait for the system trace engine to initialize before profiling.
// There is no deterministic start callback; tune this for your target devices.
private const val STARTUP_PADDING_MS = 100L
fun heavyOperation() {
// Background computations 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());
setupProfileUploadWorker(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(32768);
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();
}
示例代码通过以下步骤设置和管理分析会话:
设置执行程序。创建一个
Executor来定义将接收分析结果的线程。性能分析在后台进行。如果您稍后向回调添加更多处理,使用非界面线程执行器有助于防止出现应用无响应 (ANR) 错误。处理性能分析结果。创建一个
Consumer<ProfilingResult>对象。 系统使用此对象将ProfilingManager中的分析结果发送回您的应用。构建分析请求。创建
SystemTraceRequestBuilder以设置性能剖析会话。借助此构建器,您可以自定义ProfilingManager轨迹设置。您可以选择自定义构建器;如果不自定义,系统会使用默认设置。- 定义代码。使用
setTag()向轨迹名称添加标记。此标记有助于您识别轨迹。 - 可选:设置时长。使用
setDurationMs()指定分析时长(以毫秒为单位)。例如,60000会设置 60 秒的轨迹。如果在指定时长内未触发CancellationSignal,跟踪会在指定时长后自动结束。 - 选择缓冲政策。使用
setBufferFillPolicy()定义如何存储轨迹数据。BufferFillPolicy.RING_BUFFER表示当缓冲区已满时,新数据会覆盖最旧的数据,从而持续记录近期活动。 - 设置缓冲区大小。使用
setBufferSizeKb()为跟踪指定缓冲区空间,您可以使用该参数来控制输出跟踪记录文件的大小。
- 定义代码。使用
可选:管理会话生命周期。创建
CancellationSignal。 借助此对象,您可以随时停止分析会话,从而精确控制其时长。开始并接收结果。当您调用
requestProfiling()时,ProfilingManager会在后台启动性能分析会话。完成分析后,它会将ProfilingResult发送到您的resultCallback#accept方法。如果分析成功完成,ProfilingResult会通过ProfilingResult#getResultFilePath提供轨迹在设备上保存的路径。您可以通过编程方式获取此文件,也可以在本地进行分析时,通过在计算机上运行adb pull <trace_path>来获取此文件。添加自定义跟踪点。您可以在应用的代码中添加自定义轨迹点。在前面的代码示例中,
trace("MyApp:HeavyOperation") { ... }块会在生成的配置文件中创建一个自定义切片。