androidx.core.os


Interfaces

CancellationSignal.OnCancelListener

Listens for cancellation.

ParcelableCompatCreatorCallbacks

This interface is deprecated.

Use android.os.Parcelable.ClassLoaderCreator directly.

Classes

BufferFillPolicy
BundleCompat

Helper for accessing features in Bundle.

CancellationSignal

This class is deprecated.

This class was added to the platform in SDK 16, which is below Jetpack's minimum SDK requirement.

ConfigurationCompat

Helper class which allows access to properties of Configuration in a backward compatible fashion.

EnvironmentCompat

Helper for accessing features in Environment.

ExecutorCompat

Helper for accessing features in Executor.

HandlerCompat

Helper for accessing features in Handler.

HeapProfileRequestBuilder

Request builder to create a request for a heap profile from ProfilingManager.

JavaHeapDumpRequestBuilder

Request builder to create a request for a java heap dump from ProfilingManager.

LocaleListCompat

Helper for accessing features in LocaleList.

MessageCompat

Helper for accessing features in Message.

ParcelCompat

Helper for accessing features in Parcel.

ParcelableCompat

This class is deprecated.

Use android.os.Parcelable.ClassLoaderCreator directly.

ProcessCompat

Helper for accessing features in Process.

ProfilingRequest

Profiling request class containing data to submit a profiling request.

ProfilingRequestBuilder

Base class for request builders.

StackSamplingRequestBuilder

Request builder to create a request for stack sampling from ProfilingManager.

SystemTraceRequestBuilder

Request builder to create a request for a system trace from ProfilingManager.

TraceCompat

This class is deprecated.

TraceCompat is deprecated in favor of androidx.tracing.Trace.

UserHandleCompat

Helper for accessing features in android.os.UserHandle in a backwards compatible fashion.

UserManagerCompat

Helper for accessing features in android.os.UserManager in a backwards compatible fashion.

Exceptions

OperationCanceledException

An exception type that is thrown when an operation in progress is canceled.

Objects

BuildCompat

This class contains additional platform version checking methods for targeting pre-release versions of Android.

Annotations

BuildCompat.PrereleaseSdkCheck

Experimental feature set for pre-release SDK checks.

Top-level functions summary

Bundle

Returns a new empty Bundle.

Bundle
bundleOf(vararg pairs: Pair<StringAny?>)

Returns a new Bundle with the given key/value pairs as elements.

PersistableBundle

Returns a new empty PersistableBundle.

PersistableBundle
@RequiresApi(value = 21)
persistableBundleOf(vararg pairs: Pair<StringAny?>)

Returns a new PersistableBundle with the given key/value pairs as elements.

Flow<<Error class: unknown class>>

Obtain a flow to be called with all profiling results for this UID.

Unit
@RequiresApi(api = 35)
registerForAllProfilingResults(
    context: Context,
    executor: Executor,
    listener: Consumer<<Error class: unknown class>>
)

Register a listener to be called with all profiling results for this UID.

Unit
@RequiresApi(api = 35)
requestProfiling(
    context: Context,
    profilingRequest: ProfilingRequest,
    executor: Executor?,
    listener: Consumer<<Error class: unknown class>>?
)

Request profiling using a ProfilingRequest generated by one of the provided builders.

inline T
<T : Any?> trace(sectionName: String, block: () -> T)

This function is deprecated. Use androidx.tracing.Trace instead

Unit

Unregister a listener that was to be called for all profiling results.

Extension functions summary

OutcomeReceiver<R, E>
@RequiresApi(value = 31)
<R : Any?, E : Throwable> Continuation<R>.asOutcomeReceiver()

Returns an OutcomeReceiver that will resume this Continuation when an outcome is reported.

inline Runnable
Handler.postAtTime(
    uptimeMillis: Long,
    token: Any?,
    crossinline action: () -> Unit
)

Version of Handler.postAtTime which re-orders the parameters, allowing the action to be placed outside of parentheses.

inline Runnable
Handler.postDelayed(
    delayInMillis: Long,
    token: Any?,
    crossinline action: () -> Unit
)

Version of Handler.postDelayed which re-orders the parameters, allowing the action to be placed outside of parentheses.

PersistableBundle

Covert this map to a PersistableBundle with the key/value pairs as elements.

Top-level functions

bundleOf

fun bundleOf(): Bundle

Returns a new empty Bundle.

bundleOf

fun bundleOf(vararg pairs: Pair<StringAny?>): Bundle

Returns a new Bundle with the given key/value pairs as elements.

Throws
kotlin.IllegalArgumentException

When a value is not a supported type of Bundle.

persistableBundleOf

@RequiresApi(value = 21)
fun persistableBundleOf(): PersistableBundle

Returns a new empty PersistableBundle.

persistableBundleOf

@RequiresApi(value = 21)
fun persistableBundleOf(vararg pairs: Pair<StringAny?>): PersistableBundle

Returns a new PersistableBundle with the given key/value pairs as elements.

Supported value types are Int, Long, Double, and String and arrays of these types. On API 22 and later Boolean and BooleanArray are also supported.

Throws
kotlin.IllegalArgumentException

When a value is not a supported type of PersistableBundle.

registerForAllProfilingResults

@RequiresApi(api = 35)
fun registerForAllProfilingResults(context: Context): Flow<<Error class: unknown class>>

Obtain a flow to be called with all profiling results for this UID.

val flow = registerForAllProfilingResults(context)

flow
    .flowOn(Dispatchers.IO) // Consume files on a background thread
    .collect { profilingResult ->
        if (profilingResult.errorCode == ProfilingResult.ERROR_NONE) {
            doSomethingWithMyFile(profilingResult.resultFilePath)
        } else {
            doSomethingWithFailure(profilingResult.errorCode, profilingResult.errorMessage)
        }
    }

registerForAllProfilingResults

@RequiresApi(api = 35)
fun registerForAllProfilingResults(
    context: Context,
    executor: Executor,
    listener: Consumer<<Error class: unknown class>>
): Unit

Register a listener to be called with all profiling results for this UID.

val listener =
    Consumer<ProfilingResult> { profilingResult ->
        if (profilingResult.errorCode == ProfilingResult.ERROR_NONE) {
            doSomethingWithMyFile(profilingResult.resultFilePath)
        } else {
            doSomethingWithFailure(profilingResult.errorCode, profilingResult.errorMessage)
        }
    }

registerForAllProfilingResults(
    context,
    Dispatchers.IO.asExecutor(), // Your choice of executor for the callback to occur on.
    listener
)

requestProfiling

@RequiresApi(api = 35)
fun requestProfiling(
    context: Context,
    profilingRequest: ProfilingRequest,
    executor: Executor?,
    listener: Consumer<<Error class: unknown class>>?
): Unit

Request profiling using a ProfilingRequest generated by one of the provided builders.

If the executor and/or listener are null, and if no global listener and executor combinations are registered using registerForAllProfilingResults, the request will be dropped.

Requests will be rate limited and are not guaranteed to be filled.

There might be a delay before profiling begins. For continuous profiling types (system tracing, stack sampling, and heap profiling), we recommend starting the collection early and stopping it with cancellationSignal, set on the profilingRequest builder, immediately after the area of interest to ensure that the section you want profiled is captured. For heap dumps, we recommend testing locally to ensure that the heap dump is collected at the proper time.

val listener =
    Consumer<ProfilingResult> { profilingResult ->
        if (profilingResult.errorCode == ProfilingResult.ERROR_NONE) {
            doSomethingWithMyFile(profilingResult.resultFilePath)
        } else {
            doSomethingWithFailure(profilingResult.errorCode, profilingResult.errorMessage)
        }
    }

requestProfiling(
    context,
    JavaHeapDumpRequestBuilder()
        .setBufferSizeKb(123 /* Requested buffer size in KB */)
        .setTag("tag" /* Caller supplied tag for identification */)
        .build(),
    Dispatchers.IO.asExecutor(), // Your choice of executor for the callback to occur on.
    listener
)
val listener =
    Consumer<ProfilingResult> { profilingResult ->
        if (profilingResult.errorCode == ProfilingResult.ERROR_NONE) {
            doSomethingWithMyFile(profilingResult.resultFilePath)
        } else {
            doSomethingWithFailure(profilingResult.errorCode, profilingResult.errorMessage)
        }
    }

val cancellationSignal = CancellationSignal()

requestProfiling(
    context,
    HeapProfileRequestBuilder()
        .setBufferSizeKb(1000 /* Requested buffer size in KB */)
        .setDurationMs(5 * 1000 /* Requested profiling duration in milliseconds */)
        .setTrackJavaAllocations(true)
        .setSamplingIntervalBytes(100 /* Requested sampling interval in bytes */)
        .setTag("tag" /* Caller supplied tag for identification */)
        .setCancellationSignal(cancellationSignal)
        .build(),
    Dispatchers.IO.asExecutor(), // Your choice of executor for the callback to occur on.
    listener
)

// Optionally, wait for something interesting to happen and then stop the profiling to receive
// the result as is.
cancellationSignal.cancel()
val listener =
    Consumer<ProfilingResult> { profilingResult ->
        if (profilingResult.errorCode == ProfilingResult.ERROR_NONE) {
            doSomethingWithMyFile(profilingResult.resultFilePath)
        } else {
            doSomethingWithFailure(profilingResult.errorCode, profilingResult.errorMessage)
        }
    }

val cancellationSignal = CancellationSignal()

requestProfiling(
    context,
    StackSamplingRequestBuilder()
        .setBufferSizeKb(1000 /* Requested buffer size in KB */)
        .setDurationMs(10 * 1000 /* Requested profiling duration in millisconds */)
        .setSamplingFrequencyHz(100 /* Requested sampling frequency */)
        .setTag("tag" /* Caller supplied tag for identification */)
        .setCancellationSignal(cancellationSignal)
        .build(),
    Dispatchers.IO.asExecutor(), // Your choice of executor for the callback to occur on.
    listener
)

// Optionally, wait for something interesting to happen and then stop the profiling to receive
// the result as is.
cancellationSignal.cancel()
val listener =
    Consumer<ProfilingResult> { profilingResult ->
        if (profilingResult.errorCode == ProfilingResult.ERROR_NONE) {
            doSomethingWithMyFile(profilingResult.resultFilePath)
        } else {
            doSomethingWithFailure(profilingResult.errorCode, profilingResult.errorMessage)
        }
    }

val cancellationSignal = CancellationSignal()

requestProfiling(
    context,
    SystemTraceRequestBuilder()
        .setBufferSizeKb(1000 /* Requested buffer size in KB */)
        .setDurationMs(60 * 1000 /* Requested profiling duration in millisconds */)
        .setBufferFillPolicy(BufferFillPolicy.RING_BUFFER /* Buffer fill policy */)
        .setTag("tag" /* Caller supplied tag for identification */)
        .setCancellationSignal(cancellationSignal)
        .build(),
    Dispatchers.IO.asExecutor(), // Your choice of executor for the callback to occur on.
    listener
)

// Optionally, wait for something interesting to happen and then stop the profiling to receive
// the result as is.
cancellationSignal.cancel()

trace

Added in 1.1.0
Deprecated in 1.5.0
inline fun <T : Any?> trace(sectionName: String, block: () -> T): T

Wrap the specified block in calls to Trace.beginSection (with the supplied sectionName) and Trace.endSection.

unregisterForAllProfilingResults

@RequiresApi(api = 35)
fun unregisterForAllProfilingResults(
    context: Context,
    listener: Consumer<<Error class: unknown class>>
): Unit

Unregister a listener that was to be called for all profiling results.

Extension functions

asOutcomeReceiver

@RequiresApi(value = 31)
fun <R : Any?, E : Throwable> Continuation<R>.asOutcomeReceiver(): OutcomeReceiver<R, E>

Returns an OutcomeReceiver that will resume this Continuation when an outcome is reported.

Useful for writing suspend bindings to async Android platform methods that accept OutcomeReceiver:

public suspend fun FancinessManager.query(
query: FancinessManager.Query
): FancinessManager.QueryResult = suspendCancellableCoroutine<QueryResult> { continuation ->

// Any Android API that supports cancellation should be configured to propagate
// coroutine cancellation as follows:
val canceller = CancellationSignal()
continuation.invokeOnCancellation { canceller.cancel() }

// Invoke the FancinessManager#queryAsync method as follows:
queryAsync(
query,
canceller,
// Use a direct executor to avoid extra dispatch. Resuming the continuation will
// handle getting to the right thread or pool via the ContinuationInterceptor.
Runnable::run,
continuation.asOutcomeReceiver()
)
}

postAtTime

inline fun Handler.postAtTime(
    uptimeMillis: Long,
    token: Any? = null,
    crossinline action: () -> Unit
): Runnable

Version of Handler.postAtTime which re-orders the parameters, allowing the action to be placed outside of parentheses.

handler.postAtTime(200) {
doSomething()
}
Parameters
uptimeMillis: Long

The absolute time at which the callback should run, using the android.os.SystemClock#uptimeMillis time-base.

token: Any? = null

An optional object with which the posted message will be associated.

crossinline action: () -> Unit

The action that will be executed.

Returns
Runnable

the created Runnable

postDelayed

inline fun Handler.postDelayed(
    delayInMillis: Long,
    token: Any? = null,
    crossinline action: () -> Unit
): Runnable

Version of Handler.postDelayed which re-orders the parameters, allowing the action to be placed outside of parentheses.

handler.postDelayed(200) {
doSomething()
}
Returns
Runnable

the created Runnable

toPersistableBundle

@RequiresApi(value = 21)
fun Map<StringAny?>.toPersistableBundle(): PersistableBundle

Covert this map to a PersistableBundle with the key/value pairs as elements.

Supported value types are Int, Long, Double, and String and arrays of these types. On API 22 and later Boolean and BooleanArray are also supported.

Throws
kotlin.IllegalArgumentException

When a value is not a supported type of PersistableBundle.