Save the date! Android Dev Summit is coming to Sunnyvale, CA on Oct 23-24, 2019.

ContextCompat

open class ContextCompat
kotlin.Any
   ↳ androidx.core.content.ContextCompat

Helper for accessing features in android.content.Context.

Summary

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
open static Boolean
startActivities(@NonNull context: Context, @NonNull intents: Array<Intent!>)

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

open static Boolean
startActivities(@NonNull context: Context, @NonNull intents: Array<Intent!>, @Nullable options: Bundle?)

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

open static Unit
startActivity(@NonNull context: Context, @NonNull intent: Intent, @Nullable options: Bundle?)

Start an activity with additional launch information, if able.

open static 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.

open static Array<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.

open static Array<File!>
getExternalFilesDirs(@NonNull context: Context, @Nullable type: String?)

Returns absolute paths to application-specific directories on all external storage devices where the application can place persistent files it owns.

open static Array<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.

open static Drawable?
getDrawable(@NonNull context: Context, @DrawableRes id: Int)

Returns a drawable object associated with a particular resource ID.

open static ColorStateList?
getColorStateList(@NonNull context: Context, @ColorRes id: Int)

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

open static Int
getColor(@NonNull context: Context, @ColorRes id: Int)

Returns a color associated with a particular resource ID

open static Int
checkSelfPermission(@NonNull context: Context, @NonNull permission: String)

Determine whether you have been granted a particular permission.

open static File?
getNoBackupFilesDir(@NonNull context: Context)

Returns the absolute path to the directory on the filesystem similar to Context#getFilesDir().

open static File!
getCodeCacheDir(@NonNull context: Context)

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

open static Context?

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

open static Boolean
isDeviceProtectedStorage(@NonNull context: Context)

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

open static Executor!

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

open static Unit
startForegroundService(@NonNull context: Context, @NonNull intent: Intent)

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

open static T?
getSystemService(@NonNull context: Context, @NonNull serviceClass: Class<T>)

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

open static String?
getSystemServiceName(@NonNull context: Context, @NonNull serviceClass: Class<*>)

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

Protected constructors

<init>

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

startActivities

open static fun startActivities(@NonNull context: Context, @NonNull 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 Context: 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.
Return
Boolean: true if the underlying API was available and the call was successful, false otherwise

startActivities

open static fun startActivities(@NonNull context: Context, @NonNull intents: Array<Intent!>, @Nullable 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 Context: 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 Context: Additional options for how the Activity should be started. See android.content.Context#startActivity(Intent, android.os.Bundle)
Return
Boolean: true if the underlying API was available and the call was successful, false otherwise

startActivity

open static fun startActivity(@NonNull context: Context, @NonNull intent: Intent, @Nullable 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 Context: The description of the activity to start.
options Context: 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.

getDataDir

@Nullable open static fun getDataDir(@NonNull 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 Context#getFilesDir(), Context#getCacheDir(), Context#getDir(String, int), 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.

getObbDirs

@NonNull open static fun getObbDirs(@NonNull 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 Context#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 android.os.StatFs.

Starting in android.os.Build.VERSION_CODES#KITKAT, no permissions are required to write to the returned paths; they're always accessible to the calling app. Before then, android.Manifest.permission#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 Context#getObbDir(). Returned paths may be null if a storage device is unavailable.

getExternalFilesDirs

@NonNull open static fun getExternalFilesDirs(@NonNull context: Context, @Nullable 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 Context#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 android.os.StatFs.

Starting in android.os.Build.VERSION_CODES#KITKAT, no permissions are required to write to the returned paths; they're always accessible to the calling app. Before then, android.Manifest.permission#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 Context#getExternalFilesDir(String). Returned paths may be null if a storage device is unavailable.

getExternalCacheDirs

@NonNull open static fun getExternalCacheDirs(@NonNull 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 Context#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 android.os.StatFs.

Starting in android.os.Build.VERSION_CODES#KITKAT, no permissions are required to write to the returned paths; they're always accessible to the calling app. Before then, android.Manifest.permission#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 Context#getExternalCacheDir(). Returned paths may be null if a storage device is unavailable.

getDrawable

@Nullable open static fun getDrawable(@NonNull context: Context, @DrawableRes id: Int): Drawable?

Returns a drawable object associated with a particular resource ID.

Starting in android.os.Build.VERSION_CODES#LOLLIPOP, the returned drawable will be styled for the specified Context's theme.

Parameters
id Context: 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.
Return
Drawable?: Drawable An object that can be used to draw this resource.

getColorStateList

@Nullable open static fun getColorStateList(@NonNull context: Context, @ColorRes id: Int): ColorStateList?

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

Starting in android.os.Build.VERSION_CODES#M, the returned color state list will be styled for the specified Context's theme.

Parameters
id Context: 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.
Return
ColorStateList?: A color state list, or null if the resource could not be resolved.
Exceptions
android.content.res.Resources.NotFoundException if the given ID does not exist.

getColor

open static fun getColor(@NonNull context: Context, @ColorRes id: Int): Int

Returns a color associated with a particular resource ID

Starting in android.os.Build.VERSION_CODES#M, the returned color will be styled for the specified Context's theme.

Parameters
id Context: 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.
Return
Int: A single color value in the form 0xAARRGGBB.
Exceptions
android.content.res.Resources.NotFoundException if the given ID does not exist.

checkSelfPermission

open static fun checkSelfPermission(@NonNull context: Context, @NonNull permission: String): Int

Determine whether you have been granted a particular permission.

Parameters
permission Context: The name of the permission being checked.
Return
Int: android.content.pm.PackageManager#PERMISSION_GRANTED if you have the permission, or android.content.pm.PackageManager#PERMISSION_DENIED if not.

getNoBackupFilesDir

@Nullable open static fun getNoBackupFilesDir(@NonNull context: Context): File?

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

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

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

getCodeCacheDir

open static fun getCodeCacheDir(@NonNull context: Context): File!

Returns the absolute path to the application specific cache directory on the filesystem designed for storing cached code. On devices running android.os.Build.VERSION_CODES#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.

Return
File!: The path of the directory holding application code cache files.

createDeviceProtectedStorageContext

@Nullable open static fun createDeviceProtectedStorageContext(@NonNull 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.

isDeviceProtectedStorage

open static fun isDeviceProtectedStorage(@NonNull context: Context): Boolean

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

getMainExecutor

open 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).

startForegroundService

open static fun startForegroundService(@NonNull context: Context, @NonNull intent: Intent): Unit

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

Parameters
context Context: Context to start Service from.
intent Context: The description of the Service to start.

getSystemService

@Nullable open static fun <T : Any!> getSystemService(@NonNull context: Context, @NonNull serviceClass: Class<T>): T?

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

Parameters
context Context: Context to retrieve service from.
serviceClass Context: The class of the desired service.
Return
T?: The service or null if the class is not a supported system service.

getSystemServiceName

@Nullable open static fun getSystemServiceName(@NonNull context: Context, @NonNull serviceClass: Class<*>): 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 Context: The class of the desired service.
Return
String?: The service name or null if the class is not a supported system service.