androidx.core.content


Interfaces

OnConfigurationChangedProvider

Interface for components that can dispatch calls from ComponentCallbacks.onConfigurationChanged.

OnTrimMemoryProvider

Interface for components that can dispatch calls from ComponentCallbacks2.onTrimMemory.

Classes

ContentProviderCompat

Helper for accessing features in android.content.ContentProvider in a backwards compatible fashion.

ContentResolverCompat

Helper for accessing features in ContentResolver in a backwards compatible fashion.

ContextCompat

Helper for accessing features in Context.

FileProvider

FileProvider is a special subclass of ContentProvider that facilitates secure sharing of files associated with an app by creating a content://Uri for a file instead of a file:///Uri.

IntentCompat

Helper for accessing features in Intent.

IntentSanitizer

This class is used to make a sanitized copy of an Intent.

IntentSanitizer.Builder

General strategy of building is to only offer additive “or” operations that are chained together.

LocusIdCompat

An identifier for an unique state (locus) in the application.

MimeTypeFilter

Provides utility methods for matching MIME type filters used in ContentProvider.

PackageManagerCompat

Helper for accessing features in PackageManager.

PermissionChecker

This class provides permission check APIs that verify both the permission and the associated app op for this permission if such is defined.

SharedPreferencesCompat

This class is deprecated.

This compatibility class is no longer required.

SharedPreferencesCompat.EditorCompat

This class is deprecated.

This compatibility class is no longer required.

UnusedAppRestrictionsBackportCallback

Wrapper class for {IUnusedAppRestrictionsBackportCallback}.

UnusedAppRestrictionsBackportService

Wrapper class for IUnusedAppRestrictionsBackportService.

UnusedAppRestrictionsConstants

Shared constants related to Unused App Restrictions (e.g. Permission Revocation, App Hibernation).

UriMatcherCompat

Helper for accessing UriMatcher to create Uri Predicate.

Top-level functions summary

ContentValues
contentValuesOf(vararg pairs: Pair<StringAny?>)

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

Extension functions summary

inline Unit

Allows editing of this preference instance with a call to apply or commit to persist the changes.

inline T?

Return the handle to a system-level service by class.

suspend Nothing
Context.receiveBroadcasts(
    filter: IntentFilter,
    flags: Int,
    broadcastPermission: String?,
    scheduler: Handler?,
    onReceive: BroadcastReceiver.(Intent?) -> Unit
)

Registers a BroadcastReceiver until the coroutine is cancelled.

suspend Nothing
Context.receiveBroadcastsAsync(
    filter: IntentFilter,
    flags: Int,
    broadcastPermission: String?,
    scheduler: Handler?,
    onReceive: suspend BroadcastReceiver.PendingResult.(Intent?) -> Unit
)

Register a BroadcastReceiver until the coroutine is cancelled.

inline Unit
Context.withStyledAttributes(
    resourceId: @StyleRes Int,
    attrs: IntArray,
    block: TypedArray.() -> Unit
)

Executes block on a TypedArray receiver.

inline Unit
Context.withStyledAttributes(
    set: AttributeSet?,
    attrs: IntArray,
    defStyleAttr: @AttrRes Int,
    defStyleRes: @StyleRes Int,
    block: TypedArray.() -> Unit
)

Executes block on a TypedArray receiver.

Top-level functions

contentValuesOf

fun contentValuesOf(vararg pairs: Pair<StringAny?>): ContentValues

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

Throws
kotlin.IllegalArgumentException

When a value is not a supported type of ContentValues.

Extension functions

edit

inline fun SharedPreferences.edit(commit: Boolean = false, action: SharedPreferences.Editor.() -> Unit): Unit

Allows editing of this preference instance with a call to apply or commit to persist the changes. Default behaviour is apply.

prefs.edit {
putString("key", value)
}

To commit changes:

prefs.edit(commit = true) {
putString("key", value)
}

getSystemService

inline fun <T : Any> Context.getSystemService(): T?

Return the handle to a system-level service by class.

See also
getSystemService

receiveBroadcasts

suspend fun Context.receiveBroadcasts(
    filter: IntentFilter,
    flags: Int,
    broadcastPermission: String? = null,
    scheduler: Handler? = null,
    onReceive: BroadcastReceiver.(Intent?) -> Unit
): Nothing

Registers a BroadcastReceiver until the coroutine is cancelled.

Equivalent to calling ContextCompat.registerReceiver, and when the coroutine is cancelled calling Context.unregisterReceiver, but exceptions from onReceive will propagate to the caller (unregistering the receiver in the process).

The rules of BroadcastReceiver.onReceive apply here. You can use the receiver BroadcastReceiver to view/modify the current result values.

onReceive runs on the provided scheduler thread, or the main thread if it's null. This means it can continue running even after receiveBroadcasts is cancelled. To propagate cancellation, consider using receiveBroadcastsAsync.

If you wish to process broadcasts asynchronously (and concurrently), consider using receiveBroadcastsAsync, or manually use BroadcastReceiver.goAsync.

Example usage:

import android.app.Activity.RESULT_OK
import
android.content.Intent
import
android.content.IntentFilter
import
androidx.core.content.ContextCompat
import
androidx.core.content.receiveBroadcasts
import
kotlinx.coroutines.coroutineScope

coroutineScope
{
val job = launch {
context.receiveBroadcasts(
filter = IntentFilter(Intent.ACTION_TIME_CHANGED),
flags = ContextCompat.RECEIVER_EXPORTED,
) { intent: Intent? ->
// Process intent
setResultCode(RESULT_OK) // Set broadcast result
}
}
...
job.cancel() // Unregister
}
Parameters
filter: IntentFilter

Selects the Intent broadcasts to be received.

flags: Int

If this receiver is listening for broadcasts sent from other apps - even other apps that you own - use the ContextCompat.RECEIVER_EXPORTED flag. If instead this receiver is listening only for broadcasts sent by your app, or from the system UID, use the ContextCompat.RECEIVER_NOT_EXPORTED flag.

broadcastPermission: String? = null

String naming a permission that a broadcaster must hold in order to send and Intent to you. If null, no permission is required.

scheduler: Handler? = null

Handler identifying the thread will receive the Intent. If null, the main thread of the process will be used.

onReceive: BroadcastReceiver.(Intent?) -> Unit

The callback equivalent of BroadcastReceiver.onReceive, taking the BroadcastReceiver as a receiver.

receiveBroadcastsAsync

suspend fun Context.receiveBroadcastsAsync(
    filter: IntentFilter,
    flags: Int,
    broadcastPermission: String? = null,
    scheduler: Handler? = null,
    onReceive: suspend BroadcastReceiver.PendingResult.(Intent?) -> Unit
): Nothing

Register a BroadcastReceiver until the coroutine is cancelled.

Equivalent to calling ContextCompat.registerReceiver, and when the coroutine is cancelled calling Context.unregisterReceiver, but uses BroadcastReceiver.goAsync to allow suspending onReceive and calls BroadcastReceiver.PendingResult.finish when onReceive returns or throws.

The rules of BroadcastReceiver.goAsync apply here. You can use the receiver BroadcastReceiver.PendingResult to view/modify the current result values. If you wish to use the BroadcastReceiver, consider using receiveBroadcasts.

Each onReceive is invoked concurrently in a child coroutine of the current context, and is cancelled when receiveBroadcastsAsync is cancelled. If any onReceive throws, all other concurrent invocations are cancelled and the exception is propagated to the caller (unregistering the receiver in the process).

Do not call BroadcastReceiver.PendingResult.finish yourself, this is done for you when onReceive returns or throws.

Example usage:

import android.app.Activity.RESULT_OK
import
android.content.Intent
import
android.content.IntentFilter
import
androidx.core.content.ContextCompat
import
androidx.core.content.receiveBroadcasts
import
kotlinx.coroutines.coroutineScope
import
kotlinx.coroutines.delay

coroutineScope
{
val job = launch {
context.receiveBroadcastsAsync(
filter = IntentFilter(Intent.ACTION_TIME_CHANGED),
flags = ContextCompat.RECEIVER_EXPORTED,
) { intent: Intent? ->
delay(100) // Process intent with suspending work
setResultCode(RESULT_OK) // Set broadcast result
}
}
...
job.cancel() // Unregister and cancel ongoing callbacks.
}
Parameters
filter: IntentFilter

Selects the Intent broadcasts to be received.

flags: Int

If this receiver is listening for broadcasts sent from other apps - even other apps that you own - use the ContextCompat.RECEIVER_EXPORTED flag. If instead this receiver is listening only for broadcasts sent by your app, or from the system UID, use the ContextCompat.RECEIVER_NOT_EXPORTED flag.

broadcastPermission: String? = null

String naming a permission that a broadcaster must hold in order to send and Intent to you. If null, no permission is required.

scheduler: Handler? = null

Handler identifying the thread will receive the Intent. If null, the main thread of the process will be used. Note that this is not used to run onReceive, but if the handler is blocked onReceive will not execute.

onReceive: suspend BroadcastReceiver.PendingResult.(Intent?) -> Unit

The callback equivalent of BroadcastReceiver.onReceive, taking the BroadcastReceiver.PendingResult as receiver.

withStyledAttributes

inline fun Context.withStyledAttributes(
    resourceId: @StyleRes Int,
    attrs: IntArray,
    block: TypedArray.() -> Unit
): Unit

Executes block on a TypedArray receiver. The TypedArray holds the values defined by the style resource resourceId which are listed in attrs.

Parameters
resourceId: @StyleRes Int

The desired style resource.

attrs: IntArray

The desired attributes. These attribute IDs must be sorted in ascending order.

block: TypedArray.() -> Unit

The block that will be executed.

withStyledAttributes

inline fun Context.withStyledAttributes(
    set: AttributeSet? = null,
    attrs: IntArray,
    defStyleAttr: @AttrRes Int = 0,
    defStyleRes: @StyleRes Int = 0,
    block: TypedArray.() -> Unit
): Unit

Executes block on a TypedArray receiver. The TypedArray holds the attribute values in set that are listed in attrs. In addition, if the given AttributeSet specifies a style class (through the style attribute), that style will be applied on top of the base attributes it defines.

Parameters
set: AttributeSet? = null

The base set of attribute values.

attrs: IntArray

The desired attributes to be retrieved. These attribute IDs must be sorted in ascending order.

defStyleAttr: @AttrRes Int = 0

An attribute in the current theme that contains a reference to a style resource that supplies defaults values for the TypedArray. Can be 0 to not look for defaults.

defStyleRes: @StyleRes Int = 0

A resource identifier of a style resource that supplies default values for the TypedArray, used only if defStyleAttr is 0 or can not be found in the theme. Can be 0 to not look for defaults.

block: TypedArray.() -> Unit

The block that will be executed.