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(@DisplayContext @NonNull 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
@DisplayContext @NonNull 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.