Define custom events

System tracing shows you information about processes only at the system level, so it's sometimes difficult to know which of your app or game's methods are executing at a given time relative to system events.

Jetpack provides a tracing API that you can use to label a particular section of code. This information is then reported in traces captured on the device. Macrobenchmark captures traces with custom trace points automatically.

When using the systrace command line tool to capture traces, the-aoption is required. Without this option, your app's methods don't appear in a system trace report.

Kotlin

classMyAdapter:RecyclerView.Adapter<MyViewHolder>(){
overridefunonCreateViewHolder(parent:ViewGroup,
viewType:Int):MyViewHolder{
trace("MyAdapter.onCreateViewHolder"){
MyViewHolder.newInstance(parent)
}
}

overridefunonBindViewHolder(holder:MyViewHolder,position:Int){
trace("MyAdapter.onBindViewHolder"){
trace("MyAdapter.queryDatabase")
valrowItem=queryDatabase(position)
dataset.add(rowItem)
}
holder.bind(dataset[position])
}
}
}

Java

publicclassMyAdapterextendsRecyclerView.Adapter<MyViewHolder>{
@NonNull
@Override
publicMyViewHolderonCreateViewHolder(@NonNullViewGroupparent,intviewType){
returnTraceKt.trace(
"MyAdapter.onCreateViewHolder",
()->MyViewHolder.newInstance(parent)
);
}

@Override
publicvoidonBindViewHolder(@NonNullMyViewHolderholder,intposition){
TraceKt.trace(
"MyAdapter.onBindViewHolder",
()->{
TraceKt.trace(
"MyAdapter.queryDatabase",
()->{
ItemrowItem=queryDatabase(position);
dataset.add(rowItem);
}
);
}
);
}
}

We recommend using the Kotlin extension function, even in Java code, as it automatically ends the trace when the lambda completes. This removes the risk of forgetting to end the tracing.

You can also use an NDK API for custom trace events. To learn about using this API for your native code, seeCustom trace events in native code.