ContextCompat

Added in 1.1.0

public class ContextCompat

Known direct subclasses
ActivityCompat

Helper for accessing features in android.app.Activity.


Helper for accessing features in Context.

Summary

Constants

static final int

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

static final int

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

static final 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 methods

static int

Determine whether you have been granted a particular permission.

static @NonNull Context
createAttributionContext(
    @NonNull Context context,
    @Nullable String attributionTag
)

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

static @Nullable Context

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

static @Nullable String

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

static @NonNull File

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

static @ColorInt int
getColor(@NonNull Context context, @ColorRes int id)

Returns a color associated with a particular resource ID

static @Nullable ColorStateList

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

static @NonNull Context

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

static @Nullable File

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

static @NonNull 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.

static @Nullable Drawable
getDrawable(@NonNull Context context, @DrawableRes int id)

Returns a drawable object associated with a particular resource ID.

static @NonNull File[]
@ReplaceWith(expression = "context.getExternalCacheDirs()")
getExternalCacheDirs(@NonNull Context context)

This method is deprecated.

Call getExternalCacheDirs directly.

static @NonNull File[]
@ReplaceWith(expression = "context.getExternalFilesDirs(type)")
getExternalFilesDirs(@NonNull Context context, @Nullable String type)

This method is deprecated.

Call getExternalFilesDirs directly.

static @NonNull Executor

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

static @Nullable File

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

static @NonNull File[]
@ReplaceWith(expression = "context.getObbDirs()")
getObbDirs(@NonNull Context context)

This method is deprecated.

Call getObbDirs directly.

static @NonNull String
getString(@NonNull Context context, int resId)

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

static @Nullable T
<T> getSystemService(
    @NonNull Context context,
    @NonNull Class<T> serviceClass
)

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

static @Nullable String
getSystemServiceName(
    @NonNull Context context,
    @NonNull Class<Object> serviceClass
)

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

static boolean

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

static @Nullable Intent
registerReceiver(
    @NonNull Context context,
    @Nullable BroadcastReceiver receiver,
    @NonNull IntentFilter filter,
    int flags
)

Register a broadcast receiver.

static @Nullable Intent
registerReceiver(
    @NonNull Context context,
    @Nullable BroadcastReceiver receiver,
    @NonNull IntentFilter filter,
    @Nullable String broadcastPermission,
    @Nullable Handler scheduler,
    int flags
)

Register a broadcast receiver.

static boolean
startActivities(@NonNull Context context, @NonNull Intent[] intents)

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

static boolean
startActivities(
    @NonNull Context context,
    @NonNull Intent[] intents,
    @Nullable Bundle options
)

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

static void
@ReplaceWith(expression = "context.startActivity(intent, options)")
startActivity(
    @NonNull Context context,
    @NonNull Intent intent,
    @Nullable Bundle options
)

This method is deprecated.

Call startActivity directly.

static void

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

Constants

RECEIVER_EXPORTED

Added in 1.9.0
public static final int RECEIVER_EXPORTED = 2

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
public static final int RECEIVER_NOT_EXPORTED = 4

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
public static final int RECEIVER_VISIBLE_TO_INSTANT_APPS = 1

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 methods

checkSelfPermission

Added in 1.1.0
public static int checkSelfPermission(@NonNull Context context, @NonNull String permission)

Determine whether you have been granted a particular permission.

Parameters
@NonNull Context context

context for which to check the permission.

@NonNull String permission

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
public static @NonNull Context createAttributionContext(
    @NonNull Context context,
    @Nullable String attributionTag
)

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
@NonNull Context context

The current context.

@Nullable String attributionTag

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

Returns
@NonNull Context

A Context that is tagged for the new attribution

createDeviceProtectedStorageContext

Added in 1.1.0
public static @Nullable Context createDeviceProtectedStorageContext(@NonNull 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
public static @Nullable String getAttributionTag(@NonNull Context context)

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
@Nullable String

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

getCodeCacheDir

Added in 1.1.0
public static @NonNull File getCodeCacheDir(@NonNull Context context)

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
@NonNull File

The path of the directory holding application code cache files.

getColor

Added in 1.1.0
public static @ColorInt int getColor(@NonNull Context context, @ColorRes int id)

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
@NonNull Context context

context to use for getting the color.

@ColorRes int id

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
public static @Nullable ColorStateList getColorStateList(@NonNull Context context, @ColorRes int id)

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
@NonNull Context context

context to use for getting the color state list.

@ColorRes int id

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
@Nullable 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
public static @NonNull Context getContextForLanguage(@NonNull 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
public static @Nullable File getDataDir(@NonNull Context context)

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
public static @NonNull Display getDisplayOrDefault(@NonNull @DisplayContext Context context)

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
@NonNull @DisplayContext Context context

Context to obtain the associated display

Returns
@NonNull 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
public static @Nullable Drawable getDrawable(@NonNull Context context, @DrawableRes int id)

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
@NonNull Context context

context to use for getting the drawable.

@DrawableRes int id

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
@Nullable 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()")
public static @NonNull File[] getExternalCacheDirs(@NonNull Context context)

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)")
public static @NonNull File[] getExternalFilesDirs(@NonNull Context context, @Nullable String type)

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
public static @NonNull Executor getMainExecutor(@NonNull Context context)

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
public static @Nullable File getNoBackupFilesDir(@NonNull Context context)

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
@Nullable 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()")
public static @NonNull File[] getObbDirs(@NonNull Context context)

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
public static @NonNull String getString(@NonNull Context context, int resId)

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
public static @Nullable T <T> getSystemService(
    @NonNull Context context,
    @NonNull Class<T> serviceClass
)

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

Parameters
@NonNull Context context

Context to retrieve service from.

@NonNull Class<T> serviceClass

The class of the desired service.

Returns
@Nullable T

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

See also
getSystemService

getSystemServiceName

Added in 1.1.0
public static @Nullable String getSystemServiceName(
    @NonNull Context context,
    @NonNull Class<Object> serviceClass
)

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

Parameters
@NonNull Context context

Context to retrieve service name from.

@NonNull Class<Object> serviceClass

The class of the desired service.

Returns
@Nullable String

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

isDeviceProtectedStorage

Added in 1.1.0
public static boolean isDeviceProtectedStorage(@NonNull Context context)

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

registerReceiver

Added in 1.9.0
public static @Nullable Intent registerReceiver(
    @NonNull Context context,
    @Nullable BroadcastReceiver receiver,
    @NonNull IntentFilter filter,
    int flags
)

Register a broadcast receiver.

Parameters
@Nullable BroadcastReceiver receiver

The BroadcastReceiver to handle the broadcast.

@NonNull Context context

Context to retrieve service from.

@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 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
@Nullable 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
public static @Nullable Intent registerReceiver(
    @NonNull Context context,
    @Nullable BroadcastReceiver receiver,
    @NonNull IntentFilter filter,
    @Nullable String broadcastPermission,
    @Nullable Handler scheduler,
    int flags
)

Register a broadcast receiver.

Parameters
@Nullable BroadcastReceiver receiver

The BroadcastReceiver to handle the broadcast.

@NonNull Context context

Context to retrieve service from.

@NonNull IntentFilter filter

Selects the Intent broadcasts to be received.

@Nullable 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.

@Nullable Handler scheduler

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

int flags

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
@Nullable 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
public static boolean startActivities(@NonNull Context context, @NonNull Intent[] intents)

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
@NonNull Context context

Start activities using this activity as the starting context

@NonNull Intent[] intents

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
public static boolean startActivities(
    @NonNull Context context,
    @NonNull Intent[] intents,
    @Nullable Bundle options
)

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
@NonNull Context context

Start activities using this activity as the starting context

@NonNull Intent[] intents

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.

@Nullable Bundle options

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)")
public static void startActivity(
    @NonNull Context context,
    @NonNull Intent intent,
    @Nullable Bundle options
)

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
@NonNull Context context

Context to launch activity from.

@NonNull Intent intent

The description of the activity to start.

@Nullable Bundle options

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
public static void startForegroundService(@NonNull Context context, @NonNull Intent intent)

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

Parameters
@NonNull Context context

Context to start Service from.

@NonNull Intent intent

The description of the Service to start.