ActivityCompat

Added in 1.1.0

public class ActivityCompat extends ContextCompat


Helper for accessing features in android.app.Activity.

Summary

Nested types

This interface is the contract for receiving the results for permission requests.

Customizable delegate that allows delegating permission compatibility methods to a custom implementation.

Protected constructors

This class should not be instantiated, but the constructor must be visible for the class to be extended (as in support-v13).

Public methods

static void

Finish this activity, and tries to finish all activities immediately below it in the current task that have the same affinity.

static void

Reverses the Activity Scene entry Transition and triggers the calling Activity to reverse its exit Transition.

static @Nullable Uri

Return information about who launched this activity.

static boolean

This method is deprecated.

Use invalidateOptionsMenu directly.

static boolean

Indicates whether this activity is launched from a bubble.

static void
static void

Cause the given Activity to be recreated with a new instance.

static @Nullable DragAndDropPermissionsCompat
requestDragAndDropPermissions(
    @NonNull Activity activity,
    @NonNull DragEvent dragEvent
)

Create DragAndDropPermissionsCompat object bound to this activity and controlling the access permissions for content URIs associated with the android.view.DragEvent.

static void
requestPermissions(
    @NonNull Activity activity,
    @NonNull String[] permissions,
    @IntRange(from = 0) int requestCode
)

Requests permissions to be granted to this application.

static @NonNull T
<T extends View> requireViewById(@NonNull Activity activity, @IdRes int id)

Finds a view that was identified by the android:id XML attribute that was processed in onCreate, or throws an IllegalArgumentException if the ID is invalid, or there is no matching view in the hierarchy.

static void

When makeSceneTransitionAnimation was used to start an Activity, callback will be called to handle shared elements on the launched Activity.

static void

When makeSceneTransitionAnimation was used to start an Activity, callback will be called to handle shared elements on the launching Activity.

static void
setLocusContext(
    @NonNull Activity activity,
    @Nullable LocusIdCompat locusId,
    @Nullable Bundle bundle
)

Sets the LocusIdCompat for this activity.

static void

Sets the permission delegate for ActivityCompat.

static boolean
shouldShowRequestPermissionRationale(
    @NonNull Activity activity,
    @NonNull String permission
)

Gets whether you should show UI with rationale before requesting a permission.

static void
startActivityForResult(
    @NonNull Activity activity,
    @NonNull Intent intent,
    int requestCode,
    @Nullable Bundle options
)

Start new activity with options, if able, for which you would like a result when it finished.

static void
startIntentSenderForResult(
    @NonNull Activity activity,
    @NonNull IntentSender intent,
    int requestCode,
    @Nullable Intent fillInIntent,
    int flagsMask,
    int flagsValues,
    int extraFlags,
    @Nullable Bundle options
)

Start new IntentSender with options, if able, for which you would like a result when it finished.

static void

Inherited Constants

From androidx.core.content.ContextCompat
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.

Inherited methods

From androidx.core.content.ContextCompat
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.

Protected constructors

ActivityCompat

Added in 1.1.0
protected ActivityCompat()

This class should not be instantiated, but the constructor must be visible for the class to be extended (as in support-v13).

Public methods

finishAffinity

Added in 1.1.0
public static void finishAffinity(@NonNull Activity activity)

Finish this activity, and tries to finish all activities immediately below it in the current task that have the same affinity.

On Android 4.1+ calling this method will call through to the native version of this method. For other platforms finish will be called instead.

finishAfterTransition

Added in 1.1.0
public static void finishAfterTransition(@NonNull Activity activity)

Reverses the Activity Scene entry Transition and triggers the calling Activity to reverse its exit Transition. When the exit Transition completes, finish is called. If no entry Transition was used, finish() is called immediately and the Activity exit Transition is run.

On Android 4.4 or lower, this method only finishes the Activity with no special exit transition.

getReferrer

Added in 1.1.0
public static @Nullable Uri getReferrer(@NonNull Activity activity)

Return information about who launched this activity. If the launching Intent contains an Intent.EXTRA_REFERRER, that will be returned as-is; otherwise, if known, an android-app: referrer URI containing the package name that started the Intent will be returned. This may return null if no referrer can be identified -- it is neither explicitly specified, nor is it known which application package was involved.

If called while inside the handling of onNewIntent, this function will return the referrer that submitted that new intent to the activity. Otherwise, it always returns the referrer of the original Intent.

Note that this is not a security feature -- you can not trust the referrer information, applications can spoof it.

invalidateOptionsMenu

Added in 1.1.0
Deprecated in 1.1.0
public static boolean invalidateOptionsMenu(Activity activity)

Invalidate the activity's options menu, if able.

Before API level 11 (Android 3.0/Honeycomb) the lifecycle of the options menu was controlled primarily by the user's operation of the hardware menu key. When the user presses down on the menu key for the first time the menu was created and prepared by calls to onCreateOptionsMenu and onPrepareOptionsMenu respectively. Subsequent presses of the menu key kept the existing instance of the Menu itself and called onPrepareOptionsMenu to give the activity an opportunity to contextually alter the menu before the menu panel was shown.

In Android 3.0+ the Action Bar forces the options menu to be built early so that items chosen to show as actions may be displayed when the activity first becomes visible. The Activity method invalidateOptionsMenu forces the entire menu to be destroyed and recreated from onCreateOptionsMenu, offering a similar though heavier-weight opportunity to change the menu's contents. Normally this functionality is used to support a changing configuration of Fragments.

Applications may use this support helper to signal a significant change in activity state that should cause the options menu to be rebuilt. If the app is running on an older platform version that does not support menu invalidation the app will still receive onPrepareOptionsMenu the next time the user presses the menu key and this method will return false. If this method returns true the options menu was successfully invalidated.

Parameters
Activity activity

Invalidate the options menu of this activity

Returns
boolean

true if this operation was supported and it completed; false if it was not available.

isLaunchedFromBubble

Added in 1.7.0
public static boolean isLaunchedFromBubble(@NonNull Activity activity)

Indicates whether this activity is launched from a bubble. A bubble is a floating shortcut on the screen that expands to show an activity. If your activity can be used normally or as a bubble, you might use this method to check if the activity is bubbled to modify any behaviour that might be different between the normal activity and the bubbled activity. For example, if you normally cancel the notification associated with the activity when you open the activity, you might not want to do that when you're bubbled as that would remove the bubble.

Returns
boolean

true if the activity is launched from a bubble.

See also
setBubbleMetadata
Builder

Compatibility behavior:

  • API 31 and above, this method matches platform behavior
  • API 29, 30, this method checks the window display ID
  • API 28 and earlier, this method is a no-op

postponeEnterTransition

Added in 1.1.0
public static void postponeEnterTransition(@NonNull Activity activity)

recreate

Added in 1.1.0
public static void recreate(@NonNull Activity activity)

Cause the given Activity to be recreated with a new instance. This version of the method allows a consistent behavior across API levels, emulating what happens on Android Pie (and newer) when running on older platforms.

Parameters
@NonNull Activity activity

The activity to recreate

requestDragAndDropPermissions

Added in 1.1.0
public static @Nullable DragAndDropPermissionsCompat requestDragAndDropPermissions(
    @NonNull Activity activity,
    @NonNull DragEvent dragEvent
)

Create DragAndDropPermissionsCompat object bound to this activity and controlling the access permissions for content URIs associated with the android.view.DragEvent.

Parameters
@NonNull Activity activity

activity for which to request the permission.

@NonNull DragEvent dragEvent

Drag event to request permission for

Returns
@Nullable DragAndDropPermissionsCompat

The DragAndDropPermissionsCompat object used to control access to the content URIs. null if no content URIs are associated with the event or if permissions could not be granted.

requestPermissions

Added in 1.1.0
public static void requestPermissions(
    @NonNull Activity activity,
    @NonNull String[] permissions,
    @IntRange(from = 0) int requestCode
)

Requests permissions to be granted to this application. These permissions must be requested in your manifest, they should not be granted to your app, and they should have protection level dangerous, regardless whether they are declared by the platform or a third-party app.

Normal permissions PROTECTION_NORMAL are granted at install time if requested in the manifest. Signature permissions PROTECTION_SIGNATURE are granted at install time if requested in the manifest and the signature of your app matches the signature of the app declaring the permissions.

Call shouldShowRequestPermissionRationale before calling this API to check if the system recommends to show a rationale dialog before asking for a permission.

If your app does not have the requested permissions the user will be presented with UI for accepting them. After the user has accepted or rejected the requested permissions you will receive a callback reporting whether the permissions were granted or not. Your activity has to implement and the results of permission requests will be delivered to its onRequestPermissionsResult method.

Note that requesting a permission does not guarantee it will be granted and your app should be able to run without having this permission.

This method may start an activity allowing the user to choose which permissions to grant and which to reject. Hence, you should be prepared that your activity may be paused and resumed. Further, granting some permissions may require a restart of you application. In such a case, the system will recreate the activity stack before delivering the result to your onRequestPermissionsResult.

When checking whether you have a permission you should use checkSelfPermission.

Calling this API for permissions already granted to your app would show UI to the user to decide whether the app can still hold these permissions. This can be useful if the way your app uses the data guarded by the permissions changes significantly.

You cannot request a permission if your activity sets noHistory to true in the manifest because in this case the activity would not receive result callbacks including onRequestPermissionsResult.

The RuntimePermissions sample app demonstrates how to use this method to request permissions at run time.

If POST_NOTIFICATIONS is requested before the device supports the notification permission, then POST_NOTIFICATIONS will be removed from onRequestPermissionsResult. For devices that don't support POST_NOTIFICATIONS, apps can send users to its notification settings to enable notifications. See android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS for more information on launching notification settings.

Parameters
@NonNull Activity activity

The target activity.

@NonNull String[] permissions

The requested permissions. Must be non-null and not empty.

@IntRange(from = 0) int requestCode

Application specific request code to match with a result reported to onRequestPermissionsResult. Should be >= 0.

requireViewById

Added in 1.1.0
public static @NonNull T <T extends View> requireViewById(@NonNull Activity activity, @IdRes int id)

Finds a view that was identified by the android:id XML attribute that was processed in onCreate, or throws an IllegalArgumentException if the ID is invalid, or there is no matching view in the hierarchy.

Note: In most cases -- depending on compiler support -- the resulting view is automatically cast to the target class type. If the target class type is unconstrained, an explicit cast may be necessary.

Parameters
@NonNull Activity activity

activity in which to find a view.

@IdRes int id

the ID to search for

Returns
@NonNull T

a view with given ID

setEnterSharedElementCallback

Added in 1.1.0
public static void setEnterSharedElementCallback(
    @NonNull Activity activity,
    @Nullable SharedElementCallback callback
)

When makeSceneTransitionAnimation was used to start an Activity, callback will be called to handle shared elements on the launched Activity. This requires FEATURE_CONTENT_TRANSITIONS.

Parameters
@NonNull Activity activity

activity for which to set the callback.

@Nullable SharedElementCallback callback

Used to manipulate shared element transitions on the launched Activity.

setExitSharedElementCallback

Added in 1.1.0
public static void setExitSharedElementCallback(
    @NonNull Activity activity,
    @Nullable SharedElementCallback callback
)

When makeSceneTransitionAnimation was used to start an Activity, callback will be called to handle shared elements on the launching Activity. Most calls will only come when returning from the started Activity. This requires FEATURE_CONTENT_TRANSITIONS.

Parameters
@NonNull Activity activity

activity for which to set the callback.

@Nullable SharedElementCallback callback

Used to manipulate shared element transitions on the launching Activity.

setLocusContext

Added in 1.5.0
public static void setLocusContext(
    @NonNull Activity activity,
    @Nullable LocusIdCompat locusId,
    @Nullable Bundle bundle
)

Sets the LocusIdCompat for this activity. The locus id helps identify different instances of the same Activity class.

For example, a locus id based on a specific conversation could be set on a conversation app's chat Activity. The system can then use this locus id along with app's contents to provide ranking signals in various UI surfaces including sharing, notifications, shortcuts and so on.

It is recommended to set the same locus id in the shortcut's locus id using setLocusId so that the system can learn appropriate ranking signals linking the activity's locus id with the matching shortcut.

Parameters
@NonNull Activity activity

activity for which to set locus id.

@Nullable LocusIdCompat locusId

a unique, stable id that identifies this Activity instance. LocusId is an opaque ID that links this Activity's state to different Android concepts: setLocusId. LocusID is null by default or if you explicitly reset it.

@Nullable Bundle bundle

extras set or updated as part of this locus context. This may help provide additional metadata such as URLs, conversation participants specific to this Activity's context. Bundle can be null if additional metadata is not needed. Bundle should always be null for null locusId.

See also
ContentCaptureManager
ContentCaptureContext

Compatibility behavior:

  • API 30 and above, this method matches platform behavior.
  • API 29 and earlier, this method is no-op.

setPermissionCompatDelegate

Added in 1.1.0
public static void setPermissionCompatDelegate(
    @Nullable ActivityCompat.PermissionCompatDelegate delegate
)

Sets the permission delegate for ActivityCompat. Replaces the previously set delegate.

Parameters
@Nullable ActivityCompat.PermissionCompatDelegate delegate

The delegate to be set. null to clear the set delegate.

shouldShowRequestPermissionRationale

Added in 1.1.0
public static boolean shouldShowRequestPermissionRationale(
    @NonNull Activity activity,
    @NonNull String permission
)

Gets whether you should show UI with rationale before requesting a permission.

Parameters
@NonNull Activity activity

The target activity.

@NonNull String permission

A permission your app wants to request.

Returns
boolean

Whether you should show permission rationale UI.

startActivityForResult

Added in 1.1.0
public static void startActivityForResult(
    @NonNull Activity activity,
    @NonNull Intent intent,
    int requestCode,
    @Nullable Bundle options
)

Start new activity with options, if able, for which you would like a result when it finished.

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 Activity activity

Origin activity to launch from.

@NonNull Intent intent

The description of the activity to start.

int requestCode

If >= 0, this code will be returned in onActivityResult() when the activity exits.

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

startIntentSenderForResult

Added in 1.1.0
public static void startIntentSenderForResult(
    @NonNull Activity activity,
    @NonNull IntentSender intent,
    int requestCode,
    @Nullable Intent fillInIntent,
    int flagsMask,
    int flagsValues,
    int extraFlags,
    @Nullable Bundle options
)

Start new IntentSender with options, if able, for which you would like a result when it finished.

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 Activity activity

Origin activity to launch from.

@NonNull IntentSender intent

The IntentSender to launch.

int requestCode

If >= 0, this code will be returned in onActivityResult() when the activity exits.

@Nullable Intent fillInIntent

If non-null, this will be provided as the intent parameter to sendIntent.

int flagsMask

Intent flags in the original IntentSender that you would like to change.

int flagsValues

Desired values for any bits set in flagsMask

int extraFlags

Always set to 0.

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

startPostponedEnterTransition

Added in 1.1.0
public static void startPostponedEnterTransition(@NonNull Activity activity)