ContextCompat

Added in 1.1.0

class ContextCompat

Known direct subclasses
ActivityCompat

Helper for accessing features in android.app.Activity.


Helper for accessing features in Context.

Summary

Constants

const Int

Flag for registerReceiver: The receiver can receive broadcasts from other Apps.

const Int

Flag for registerReceiver: The receiver cannot receive broadcasts from other Apps.

const Int

Flag for registerReceiver: The receiver can receive broadcasts from Instant Apps.

Protected constructors

This class should not be instantiated, but the constructor must be visible for the class to be extended (ex. in ActivityCompat).

Public functions

java-static Int
checkSelfPermission(context: Context, permission: String)

Determine whether you have been granted a particular permission.

java-static Context
createAttributionContext(context: Context, attributionTag: String?)

Return a new Context object for the current Context but attribute to a different tag.

java-static Context?

Return a new Context object for the current Context but whose storage APIs are backed by device-protected storage.

java-static String?

Attribution can be used in complex apps to logically separate parts of the app.

java-static File

Returns the absolute path to the application specific cache directory on the filesystem designed for storing cached code.

java-static @ColorInt Int
getColor(context: Context, id: @ColorRes Int)

Returns a color associated with a particular resource ID

java-static ColorStateList?

Returns a color state list associated with a particular resource ID.

java-static Context

Gets the context which respects the per-app locales locale.

java-static File?
getDataDir(context: Context)

Returns the absolute path to the directory on the filesystem where all private files belonging to this app are stored.

java-static Display

Get the display this context is associated with or the default display as the fallback if the context is not associated with any Display.

java-static Drawable?
getDrawable(context: Context, id: @DrawableRes Int)

Returns a drawable object associated with a particular resource ID.

java-static Array<File!>
@ReplaceWith(expression = "context.getExternalCacheDirs()")
getExternalCacheDirs(context: Context)

This function is deprecated.

Call getExternalCacheDirs directly.

java-static Array<File!>
@ReplaceWith(expression = "context.getExternalFilesDirs(type)")
getExternalFilesDirs(context: Context, type: String?)

This function is deprecated.

Call getExternalFilesDirs directly.

java-static Executor

Return an Executor that will run enqueued tasks on the main thread associated with this context.

java-static File?

Returns the absolute path to the directory on the filesystem similar to getFilesDir.

java-static Array<File!>
@ReplaceWith(expression = "context.getObbDirs()")
getObbDirs(context: Context)

This function is deprecated.

Call getObbDirs directly.

java-static String
getString(context: Context, resId: Int)

Gets the resource string that also respects the per-app locales.

java-static T?
<T> getSystemService(context: Context, serviceClass: Class<T!>)

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

java-static String?
getSystemServiceName(context: Context, serviceClass: Class<Any!>)

Gets the name of the system-level service that is represented by the specified class.

java-static Boolean

Indicates if the storage APIs of this Context are backed by device-encrypted storage.

java-static Intent?
registerReceiver(
    context: Context,
    receiver: BroadcastReceiver?,
    filter: IntentFilter,
    flags: Int
)

Register a broadcast receiver.

java-static Intent?
registerReceiver(
    context: Context,
    receiver: BroadcastReceiver?,
    filter: IntentFilter,
    broadcastPermission: String?,
    scheduler: Handler?,
    flags: Int
)

Register a broadcast receiver.

java-static Boolean
startActivities(context: Context, intents: Array<Intent!>)

Start a set of activities as a synthesized task stack, if able.

java-static Boolean
startActivities(context: Context, intents: Array<Intent!>, options: Bundle?)

Start a set of activities as a synthesized task stack, if able.

java-static Unit
@ReplaceWith(expression = "context.startActivity(intent, options)")
startActivity(context: Context, intent: Intent, options: Bundle?)

This function is deprecated.

Call startActivity directly.

java-static Unit
startForegroundService(context: Context, intent: Intent)

startForegroundService() was introduced in O, just call startService for before O.

Constants

RECEIVER_EXPORTED

Added in 1.9.0
const val RECEIVER_EXPORTED = 2: Int

Flag for registerReceiver: The receiver can receive broadcasts from other Apps. Has the same behavior as marking a statically registered receiver with "exported=true"

RECEIVER_NOT_EXPORTED

Added in 1.9.0
const val RECEIVER_NOT_EXPORTED = 4: Int

Flag for registerReceiver: The receiver cannot receive broadcasts from other Apps. Has the same behavior as marking a statically registered receiver with "exported=false"

RECEIVER_VISIBLE_TO_INSTANT_APPS

Added in 1.9.0
const val RECEIVER_VISIBLE_TO_INSTANT_APPS = 1: Int

Flag for registerReceiver: The receiver can receive broadcasts from Instant Apps.

Protected constructors

ContextCompat

Added in 1.1.0
protected ContextCompat()

This class should not be instantiated, but the constructor must be visible for the class to be extended (ex. in ActivityCompat).

Public functions

checkSelfPermission

Added in 1.1.0
java-static fun checkSelfPermission(context: Context, permission: String): Int

Determine whether you have been granted a particular permission.

Parameters
context: Context

context for which to check the permission.

permission: String

The name of the permission being checked.

Returns
Int

PERMISSION_GRANTED if you have the permission, or PERMISSION_DENIED if not.

See also
checkPermission

createAttributionContext

Added in 1.13.0
java-static fun createAttributionContext(context: Context, attributionTag: String?): Context

Return a new Context object for the current Context but attribute to a different tag. In complex apps attribution tagging can be used to distinguish between separate logical parts.

Compatibility behavior:

  • API 30 and above, returns a new Context object with the specified attribution tag
  • API 29 and earlier, returns the original context with no attribution tag
Parameters
context: Context

The current context.

attributionTag: String?

The tag or null to create a context for the default.

Returns
Context

A Context that is tagged for the new attribution

createDeviceProtectedStorageContext

Added in 1.1.0
java-static fun createDeviceProtectedStorageContext(context: Context): Context?

Return a new Context object for the current Context but whose storage APIs are backed by device-protected storage.

On devices with direct boot, data stored in this location is encrypted with a key tied to the physical device, and it can be accessed immediately after the device has booted successfully, both before and after the user has authenticated with their credentials (such as a lock pattern or PIN).

Because device-protected data is available without user authentication, you should carefully limit the data you store using this Context. For example, storing sensitive authentication tokens or passwords in the device-protected area is strongly discouraged.

If the underlying device does not have the ability to store device-protected and credential-protected data using different keys, then both storage areas will become available at the same time. They remain as two distinct storage locations on disk, and only the window of availability changes.

Each call to this method returns a new instance of a Context object; Context objects are not shared, however common state (ClassLoader, other Resources for the same configuration) may be so the Context itself can be fairly lightweight.

Prior to API 24 this method returns null, since device-protected storage is not available.

getAttributionTag

Added in 1.6.0
java-static fun getAttributionTag(context: Context): String?

Attribution can be used in complex apps to logically separate parts of the app. E.g. a blogging app might also have a instant messaging app built in. In this case two separate tags can for used each sub-feature.

Compatibility behavior:

  • API 30 and above, returns the attribution tag or null
  • API 29 and earlier, returns null
Returns
String?

the attribution tag this context is for or null if this is the default.

getCodeCacheDir

Added in 1.1.0
java-static fun getCodeCacheDir(context: Context): File

Returns the absolute path to the application specific cache directory on the filesystem designed for storing cached code. On devices running LOLLIPOP or later, the system will delete any files stored in this location both when your specific application is upgraded, and when the entire platform is upgraded.

This location is optimal for storing compiled or optimized code generated by your application at runtime.

Apps require no extra permissions to read or write to the returned path, since this path lives in their private storage.

Returns
File

The path of the directory holding application code cache files.

getColor

Added in 1.1.0
java-static fun getColor(context: Context, id: @ColorRes Int): @ColorInt Int

Returns a color associated with a particular resource ID

Starting in M, the returned color will be styled for the specified Context's theme.

Parameters
context: Context

context to use for getting the color.

id: @ColorRes Int

The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.

Returns
@ColorInt Int

A single color value in the form 0xAARRGGBB.

Throws
android.content.res.Resources.NotFoundException

if the given ID does not exist.

getColorStateList

Added in 1.1.0
java-static fun getColorStateList(context: Context, id: @ColorRes Int): ColorStateList?

Returns a color state list associated with a particular resource ID.

Starting in M, the returned color state list will be styled for the specified Context's theme.

Parameters
context: Context

context to use for getting the color state list.

id: @ColorRes Int

The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.

Returns
ColorStateList?

A color state list, or null if the resource could not be resolved.

Throws
android.content.res.Resources.NotFoundException

if the given ID does not exist.

getContextForLanguage

Added in 1.11.0
java-static fun getContextForLanguage(context: Context): Context

Gets the context which respects the per-app locales locale. This API is specifically for developers who set the per-app locales via setApplicationLocales, but who needs to use the context out of androidx.appcompat.app.AppCompatActivity scope.

The developers can override the returned context in Application's attachBaseContext, so that developers can get the localized string via application's context.

Compatibility behavior:

  • API 17 and above, the locale in the context returned by this method will respect the the per-app locale.
  • API 16 and earlier, this method directly return the Context

getDataDir

Added in 1.1.0
java-static fun getDataDir(context: Context): File?

Returns the absolute path to the directory on the filesystem where all private files belonging to this app are stored. Apps should not use this path directly; they should instead use getFilesDir, getCacheDir, getDir, or other storage APIs on Context.

The returned path may change over time if the calling app is moved to an adopted storage device, so only relative paths should be persisted.

No additional permissions are required for the calling app to read or write files under the returned path.

See also
dataDir

getDisplayOrDefault

Added in 1.11.0
java-static fun getDisplayOrDefault(context: @DisplayContext Context): Display

Get the display this context is associated with or the default display as the fallback if the context is not associated with any Display.

Applications must use this method with Activity or a context associated with a Display via createDisplayContext or createWindowContext, or the reported Display instance is not reliable.

Parameters
context: @DisplayContext Context

Context to obtain the associated display

Returns
Display

The display associated with the Context or the default display if the context doesn't associated with any display.

getDrawable

Added in 1.1.0
java-static fun getDrawable(context: Context, id: @DrawableRes Int): Drawable?

Returns a drawable object associated with a particular resource ID.

Starting in LOLLIPOP, the returned drawable will be styled for the specified Context's theme.

Parameters
context: Context

context to use for getting the drawable.

id: @DrawableRes Int

The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.

Returns
Drawable?

Drawable An object that can be used to draw this resource.

getExternalCacheDirs

Added in 1.1.0
Deprecated in 1.15.0
@ReplaceWith(expression = "context.getExternalCacheDirs()")
java-static fun getExternalCacheDirs(context: Context): Array<File!>

Returns absolute paths to application-specific directories on all external storage devices where the application can place cache files it owns. These files are internal to the application, and not typically visible to the user as media.

This is like getCacheDir in that these files will be deleted when the application is uninstalled, however there are some important differences:

  • External files are not always available: they will disappear if the user mounts the external storage on a computer or removes it.
  • There is no security enforced with these files.

External storage devices returned here are considered a permanent part of the device, including both emulated external storage and physical media slots, such as SD cards in a battery compartment. The returned paths do not include transient devices, such as USB flash drives.

An application may store data on any or all of the returned devices. For example, an app may choose to store large files on the device with the most available space, as measured by StatFs.

Starting in KITKAT, no permissions are required to write to the returned paths; they're always accessible to the calling app. Before then, WRITE_EXTERNAL_STORAGE is required to write. Write access outside of these paths on secondary external storage devices is not available. To request external storage access in a backwards compatible way, consider using android:maxSdkVersion like this:

<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />

The first path returned is the same as getExternalCacheDir. Returned paths may be null if a storage device is unavailable.

getExternalFilesDirs

Added in 1.1.0
Deprecated in 1.15.0
@ReplaceWith(expression = "context.getExternalFilesDirs(type)")
java-static fun getExternalFilesDirs(context: Context, type: String?): Array<File!>

Returns absolute paths to application-specific directories on all external storage devices where the application can place persistent files it owns. These files are internal to the application, and not typically visible to the user as media.

This is like getFilesDir in that these files will be deleted when the application is uninstalled, however there are some important differences:

  • External files are not always available: they will disappear if the user mounts the external storage on a computer or removes it.
  • There is no security enforced with these files.

External storage devices returned here are considered a permanent part of the device, including both emulated external storage and physical media slots, such as SD cards in a battery compartment. The returned paths do not include transient devices, such as USB flash drives.

An application may store data on any or all of the returned devices. For example, an app may choose to store large files on the device with the most available space, as measured by StatFs.

Starting in KITKAT, no permissions are required to write to the returned paths; they're always accessible to the calling app. Before then, WRITE_EXTERNAL_STORAGE is required to write. Write access outside of these paths on secondary external storage devices is not available. To request external storage access in a backwards compatible way, consider using android:maxSdkVersion like this:

<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />

The first path returned is the same as getExternalFilesDir. Returned paths may be null if a storage device is unavailable.

getMainExecutor

Added in 1.1.0
java-static fun getMainExecutor(context: Context): Executor

Return an Executor that will run enqueued tasks on the main thread associated with this context. This is the thread used to dispatch calls to application components (activities, services, etc).

getNoBackupFilesDir

Added in 1.1.0
java-static fun getNoBackupFilesDir(context: Context): File?

Returns the absolute path to the directory on the filesystem similar to getFilesDir. The difference is that files placed under this directory will be excluded from automatic backup to remote storage on devices running LOLLIPOP or later.

No permissions are required to read or write to the returned path, since this path is internal storage.

Returns
File?

The path of the directory holding application files that will not be automatically backed up to remote storage.

See also
getFilesDir

getObbDirs

Added in 1.1.0
Deprecated in 1.15.0
@ReplaceWith(expression = "context.getObbDirs()")
java-static fun getObbDirs(context: Context): Array<File!>

Returns absolute paths to application-specific directories on all external storage devices where the application's OBB files (if there are any) can be found. Note if the application does not have any OBB files, these directories may not exist.

This is like getFilesDir in that these files will be deleted when the application is uninstalled, however there are some important differences:

  • External files are not always available: they will disappear if the user mounts the external storage on a computer or removes it.
  • There is no security enforced with these files.

External storage devices returned here are considered a permanent part of the device, including both emulated external storage and physical media slots, such as SD cards in a battery compartment. The returned paths do not include transient devices, such as USB flash drives.

An application may store data on any or all of the returned devices. For example, an app may choose to store large files on the device with the most available space, as measured by StatFs.

Starting in KITKAT, no permissions are required to write to the returned paths; they're always accessible to the calling app. Before then, WRITE_EXTERNAL_STORAGE is required to write. Write access outside of these paths on secondary external storage devices is not available. To request external storage access in a backwards compatible way, consider using android:maxSdkVersion like this:

<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />

The first path returned is the same as getObbDir. Returned paths may be null if a storage device is unavailable.

getString

Added in 1.11.0
java-static fun getString(context: Context, resId: Int): String

Gets the resource string that also respects the per-app locales. If developers set the per-app locales via setApplicationLocales, this API returns localized strings even if the context is not androidx.appcompat.app.AppCompatActivity.

Compatibility behavior:

  • API 17 and above, this method return the localized string that respects per-app locales.
  • API 16 and earlier, this method directly return the result of getString

getSystemService

Added in 1.1.0
java-static fun <T> getSystemService(context: Context, serviceClass: Class<T!>): T?

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

Parameters
context: Context

Context to retrieve service from.

serviceClass: Class<T!>

The class of the desired service.

Returns
T?

The service or null if the class is not a supported system service.

See also
getSystemService

getSystemServiceName

Added in 1.1.0
java-static fun getSystemServiceName(context: Context, serviceClass: Class<Any!>): String?

Gets the name of the system-level service that is represented by the specified class.

Parameters
context: Context

Context to retrieve service name from.

serviceClass: Class<Any!>

The class of the desired service.

Returns
String?

The service name or null if the class is not a supported system service.

isDeviceProtectedStorage

Added in 1.1.0
java-static fun isDeviceProtectedStorage(context: Context): Boolean

Indicates if the storage APIs of this Context are backed by device-encrypted storage.

registerReceiver

Added in 1.9.0
java-static fun registerReceiver(
    context: Context,
    receiver: BroadcastReceiver?,
    filter: IntentFilter,
    flags: Int
): Intent?

Register a broadcast receiver.

Parameters
receiver: BroadcastReceiver?

The BroadcastReceiver to handle the broadcast.

context: Context

Context to retrieve service from.

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 RECEIVER_EXPORTED flag. If instead this receiver is listening only for broadcasts sent by your app, or from the system UID, use the RECEIVER_NOT_EXPORTED flag.

Returns
Intent?

The first sticky intent found that matches filter, or null if there are none.

See also
registerReceiver
https

://developer.android.com/develop/background-work/background-tasks/broadcasts#context-registered-receivers

registerReceiver

Added in 1.9.0
java-static fun registerReceiver(
    context: Context,
    receiver: BroadcastReceiver?,
    filter: IntentFilter,
    broadcastPermission: String?,
    scheduler: Handler?,
    flags: Int
): Intent?

Register a broadcast receiver.

Parameters
receiver: BroadcastReceiver?

The BroadcastReceiver to handle the broadcast.

context: Context

Context to retrieve service from.

filter: IntentFilter

Selects the Intent broadcasts to be received.

broadcastPermission: String?

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?

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

flags: Int

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

Returns
Intent?

The first sticky intent found that matches filter, or null if there are none.

See also
registerReceiver
https

://developer.android.com/develop/background-work/background-tasks/broadcasts#context-registered-receivers

startActivities

Added in 1.1.0
java-static fun startActivities(context: Context, intents: Array<Intent!>): Boolean

Start a set of activities as a synthesized task stack, if able.

In API level 11 (Android 3.0/Honeycomb) the recommended conventions for app navigation using the back key changed. The back key's behavior is local to the current task and does not capture navigation across different tasks. Navigating across tasks and easily reaching the previous task is accomplished through the "recents" UI, accessible through the software-provided Recents key on the navigation or system bar. On devices with the older hardware button configuration the recents UI can be accessed with a long press on the Home key.

When crossing from one task stack to another post-Android 3.0, the application should synthesize a back stack/history for the new task so that the user may navigate out of the new task and back to the Launcher by repeated presses of the back key. Back key presses should not navigate across task stacks.

startActivities provides a mechanism for constructing a synthetic task stack of multiple activities. If the underlying API is not available on the system this method will return false.

Parameters
context: Context

Start activities using this activity as the starting context

intents: Array<Intent!>

Array of intents defining the activities that will be started. The element length-1 will correspond to the top activity on the resulting task stack.

Returns
Boolean

true if the underlying API was available and the call was successful, false otherwise

startActivities

Added in 1.1.0
java-static fun startActivities(context: Context, intents: Array<Intent!>, options: Bundle?): Boolean

Start a set of activities as a synthesized task stack, if able.

In API level 11 (Android 3.0/Honeycomb) the recommended conventions for app navigation using the back key changed. The back key's behavior is local to the current task and does not capture navigation across different tasks. Navigating across tasks and easily reaching the previous task is accomplished through the "recents" UI, accessible through the software-provided Recents key on the navigation or system bar. On devices with the older hardware button configuration the recents UI can be accessed with a long press on the Home key.

When crossing from one task stack to another post-Android 3.0, the application should synthesize a back stack/history for the new task so that the user may navigate out of the new task and back to the Launcher by repeated presses of the back key. Back key presses should not navigate across task stacks.

startActivities provides a mechanism for constructing a synthetic task stack of multiple activities. If the underlying API is not available on the system this method will return false.

Parameters
context: Context

Start activities using this activity as the starting context

intents: Array<Intent!>

Array of intents defining the activities that will be started. The element length-1 will correspond to the top activity on the resulting task stack.

options: Bundle?

Additional options for how the Activity should be started. See startActivity

Returns
Boolean

true if the underlying API was available and the call was successful, false otherwise

startActivity

Added in 1.1.0
Deprecated in 1.15.0
@ReplaceWith(expression = "context.startActivity(intent, options)")
java-static fun startActivity(context: Context, intent: Intent, options: Bundle?): Unit

Start an activity with additional launch information, if able.

In Android 4.1+ additional options were introduced to allow for more control on activity launch animations. Applications can use this method along with ActivityOptionsCompat to use these animations when available. When run on versions of the platform where this feature does not exist the activity will be launched normally.

Parameters
context: Context

Context to launch activity from.

intent: Intent

The description of the activity to start.

options: Bundle?

Additional options for how the Activity should be started. May be null if there are no options. See ActivityOptionsCompat for how to build the Bundle supplied here; there are no supported definitions for building it manually.

startForegroundService

Added in 1.1.0
java-static fun startForegroundService(context: Context, intent: Intent): Unit

startForegroundService() was introduced in O, just call startService for before O.

Parameters
context: Context

Context to start Service from.

intent: Intent

The description of the Service to start.