ContextKt

Added in 1.1.0

public final class ContextKt


Summary

Public methods

static final T
<T extends Object> getSystemService(@NonNull Context receiver)

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

static final @NonNull Void
receiveBroadcasts(
    @NonNull Context receiver,
    @NonNull IntentFilter filter,
    int flags,
    String broadcastPermission,
    Handler scheduler,
    @NonNull Function2<@NonNull BroadcastReceiverIntentUnit> onReceive
)

Registers a BroadcastReceiver until the coroutine is cancelled.

static final @NonNull Void
receiveBroadcastsAsync(
    @NonNull Context receiver,
    @NonNull IntentFilter filter,
    int flags,
    String broadcastPermission,
    Handler scheduler,
    @NonNull SuspendFunction2<@NonNull BroadcastReceiver.PendingResultIntentUnit> onReceive
)

Register a BroadcastReceiver until the coroutine is cancelled.

static final void
withStyledAttributes(
    @NonNull Context receiver,
    @StyleRes int resourceId,
    @NonNull int[] attrs,
    @NonNull Function1<@NonNull TypedArrayUnit> block
)

Executes block on a TypedArray receiver.

static final void
withStyledAttributes(
    @NonNull Context receiver,
    AttributeSet set,
    @NonNull int[] attrs,
    @AttrRes int defStyleAttr,
    @StyleRes int defStyleRes,
    @NonNull Function1<@NonNull TypedArrayUnit> block
)

Executes block on a TypedArray receiver.

Public methods

getSystemService

public static final T <T extends Object> getSystemService(@NonNull Context receiver)

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

See also
getSystemService

receiveBroadcasts

public static final @NonNull Void receiveBroadcasts(
    @NonNull Context receiver,
    @NonNull IntentFilter filter,
    int flags,
    String broadcastPermission,
    Handler scheduler,
    @NonNull Function2<@NonNull BroadcastReceiverIntentUnit> onReceive
)

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
@NonNull IntentFilter filter

Selects the Intent broadcasts to be received.

int flags

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.

String broadcastPermission

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

Handler scheduler

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

@NonNull Function2<@NonNull BroadcastReceiverIntentUnit> onReceive

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

receiveBroadcastsAsync

public static final @NonNull Void receiveBroadcastsAsync(
    @NonNull Context receiver,
    @NonNull IntentFilter filter,
    int flags,
    String broadcastPermission,
    Handler scheduler,
    @NonNull SuspendFunction2<@NonNull BroadcastReceiver.PendingResultIntentUnit> onReceive
)

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
@NonNull IntentFilter filter

Selects the Intent broadcasts to be received.

int flags

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.

String broadcastPermission

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

Handler scheduler

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.

@NonNull SuspendFunction2<@NonNull BroadcastReceiver.PendingResultIntentUnit> onReceive

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

withStyledAttributes

public static final void withStyledAttributes(
    @NonNull Context receiver,
    @StyleRes int resourceId,
    @NonNull int[] attrs,
    @NonNull Function1<@NonNull TypedArrayUnit> block
)

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

Parameters
@StyleRes int resourceId

The desired style resource.

@NonNull int[] attrs

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

@NonNull Function1<@NonNull TypedArrayUnit> block

The block that will be executed.

withStyledAttributes

public static final void withStyledAttributes(
    @NonNull Context receiver,
    AttributeSet set,
    @NonNull int[] attrs,
    @AttrRes int defStyleAttr,
    @StyleRes int defStyleRes,
    @NonNull Function1<@NonNull TypedArrayUnit> block
)

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
AttributeSet set

The base set of attribute values.

@NonNull int[] attrs

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

@AttrRes int defStyleAttr

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.

@StyleRes int defStyleRes

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.

@NonNull Function1<@NonNull TypedArrayUnit> block

The block that will be executed.