ComponentActivity
public class ComponentActivity extends Activity implements LifecycleOwner, ContextAware, ViewModelStoreOwner, HasDefaultViewModelProviderFactory, SavedStateRegistryOwner, OnBackPressedDispatcherOwner, NavigationEventDispatcherOwner, ActivityResultRegistryOwner, ActivityResultCaller, OnConfigurationChangedProvider, OnTrimMemoryProvider, OnNewIntentProvider, OnMultiWindowModeChangedProvider, PictureInPictureProvider, MenuHost, FullyDrawnReporterOwner
| java.lang.Object | |||||
| ↳ | android.content.Context | ||||
| ↳ | android.content.ContextWrapper | ||||
| ↳ | android.view.ContextThemeWrapper | ||||
| ↳ | android.app.Activity | ||||
| ↳ | androidx.activity.ComponentActivity |
FragmentActivity |
Base class for activities that want to use the support-based |
AppCompatActivity |
Base class for activities that wish to use some of the newer platform features on older Android devices. |
BaseCarAppActivity |
Core logic for CarAppLibrary Activity interaction with a host. |
CarAppActivity |
The class representing a car app activity in the main display. |
LauncherActivity |
This class handles providing the right launcher activity when running native applications and Car App Library applications. |
Base class for activities that enables composition of higher level components.
Rather than all functionality being built directly into this class, only the minimal set of lower level building blocks are included. Higher level components can then be used as needed without enforcing a deep Activity class hierarchy or strong coupling between components.
Summary
Public constructors |
|---|
@ContentViewAlternate constructor that can be used to provide a default layout that will be inflated as part of |
Public methods |
|
|---|---|
void |
addContentView(View view, ViewGroup.LayoutParams params) |
void |
addMenuProvider(@NonNull MenuProvider provider)Adds the given |
void |
addMenuProvider(Adds the given |
void |
addMenuProvider(Adds the given |
final void |
addOnConfigurationChangedListener(Add a new listener that will get a callback associated with |
final void |
{@inheritDoc} |
final void |
addOnMultiWindowModeChangedListener(Add a new listener that will get a callback associated with |
final void |
addOnNewIntentListener(@NonNull Consumer<@NonNull Intent> listener)Add a new listener that will get a callback associated with |
final void |
addOnPictureInPictureModeChangedListener(Add a new listener that will get a callback associated with |
final void |
addOnPictureInPictureUiStateChangedListener(Add a new listener that will get a callback associated with |
final void |
addOnTrimMemoryListener(@NonNull Consumer<@NonNull Integer> listener)Add a new listener that will get a callback associated with |
final void |
addOnUserLeaveHintListener(@NonNull Runnable listener)Add a new listener that will get a callback associated with |
final void |
Available since API 24 in the framework Activity class, puts the activity in picture-in-picture mode if possible in the current system state. |
final @NonNull ActivityResultRegistry |
Get the |
@NonNull CreationExtras |
{@inheritDoc} |
@NonNull ViewModelProvider.Factory |
|
@NonNull FullyDrawnReporter |
Retrieve the |
Object |
This method is deprecated. Use a {@link androidx.lifecycle.ViewModel} to store non config state. |
@NonNull Lifecycle |
{@inheritDoc} |
@NonNull NavigationEventDispatcher |
Lazily provides a |
final @NonNull OnBackPressedDispatcher |
Retrieve the |
final @NonNull SavedStateRegistry |
|
@NonNull ViewModelStore |
Returns the |
void |
Sets the view tree owners before setting the content view so that the inflation process and attach listeners will see them already present. |
void |
Invalidates the |
void |
This method is deprecated. This method has been deprecated in favor of using the {@link OnBackPressedDispatcher} via {@link #getOnBackPressedDispatcher()}. |
void |
@CallSuper{@inheritDoc} |
boolean |
onCreatePanelMenu(int featureId, @NonNull Menu menu) |
boolean |
onMenuItemSelected(int featureId, @NonNull MenuItem item) |
void |
@CallSuperThis method is deprecated. Deprecated in android.app.Activity |
void |
@RequiresApi(api = 26){@inheritDoc} |
void |
onPanelClosed(int featureId, @NonNull Menu menu) |
void |
@CallSuperThis method is deprecated. Deprecated in android.app.Activity |
void |
@RequiresApi(api = 26){@inheritDoc} |
void |
@RequiresApi(api = 31){@inheritDoc} |
boolean |
onPreparePanel(int featureId, View view, @NonNull Menu menu) |
void |
@CallSuperThis method is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an {@link ActivityResultContract} and the prebuilt contracts for common intents available in {@link androidx.activity.result.contract.ActivityResultContracts}, provides hooks for testing, and allow receiving results in separate, testable classes independent from your activity. |
Object |
This method is deprecated. Use a {@link androidx.lifecycle.ViewModel} to store non config state. |
final Object |
Retain all appropriate non-config state. |
void |
@CallSuper{@inheritDoc} |
Context |
Get the |
final @NonNull ActivityResultLauncher<@NonNull I> |
<I extends Object, O extends Object> registerForActivityResult(Register a request to |
final @NonNull ActivityResultLauncher<@NonNull I> |
<I extends Object, O extends Object> registerForActivityResult(Register a request to |
void |
removeMenuProvider(@NonNull MenuProvider provider)Removes the given |
final void |
removeOnConfigurationChangedListener(Remove a previously added listener. |
final void |
Remove a |
final void |
removeOnMultiWindowModeChangedListener(Remove a previously added listener. |
final void |
removeOnNewIntentListener(@NonNull Consumer<@NonNull Intent> listener)Remove a previously added listener. |
final void |
removeOnPictureInPictureModeChangedListener(Remove a previously added listener. |
final void |
removeOnPictureInPictureUiStateChangedListener(Remove a previously added listener. |
final void |
removeOnTrimMemoryListener(@NonNull Consumer<@NonNull Integer> listener)Remove a previously added listener. |
final void |
removeOnUserLeaveHintListener(@NonNull Runnable listener)Remove a previously added listener. |
void |
|
void |
setContentView(@LayoutRes int layoutResID) |
void |
setContentView(View view) |
void |
setContentView(View view, ViewGroup.LayoutParams params) |
final void |
Available since API 26 in the framework Activity class, updates the properties of the picture-in-picture activity, or sets it to be used later when |
void |
This method is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an {@link ActivityResultContract} and the prebuilt contracts for common intents available in {@link androidx.activity.result.contract.ActivityResultContracts}, provides hooks for testing, and allow receiving results in separate, testable classes independent from your activity. |
void |
This method is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an {@link ActivityResultContract} and the prebuilt contracts for common intents available in {@link androidx.activity.result.contract.ActivityResultContracts}, provides hooks for testing, and allow receiving results in separate, testable classes independent from your activity. |
void |
This method is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an {@link ActivityResultContract} and the prebuilt contracts for common intents available in {@link androidx.activity.result.contract.ActivityResultContracts}, provides hooks for testing, and allow receiving results in separate, testable classes independent from your activity. |
void |
This method is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an {@link ActivityResultContract} and the prebuilt contracts for common intents available in {@link androidx.activity.result.contract.ActivityResultContracts}, provides hooks for testing, and allow receiving results in separate, testable classes independent from your activity. |
Protected methods |
|
|---|---|
void |
@CallSuperThis method is deprecated. This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an {@link ActivityResultContract} and the prebuilt contracts for common intents available in {@link androidx.activity.result.contract.ActivityResultContracts}, provides hooks for testing, and allow receiving results in separate, testable classes independent from your activity. |
void |
{@inheritDoc} |
void |
@CallSuper{@inheritDoc} |
void |
@CallSuper |
void |
{@inheritDoc} |
Inherited methods |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Public constructors
ComponentActivity
@ContentView
public ComponentActivity(@LayoutRes int contentLayoutId)
Alternate constructor that can be used to provide a default layout that will be inflated as part of super.onCreate(savedInstanceState).
This should generally be called from your constructor that takes no parameters, as is required for API 27 and lower or when using the default android.app.AppComponentFactory.
Public methods
addMenuProvider
public void addMenuProvider(@NonNull MenuProvider provider)
Adds the given MenuProvider to this MenuHost. If using this method, you must manually remove the provider when necessary.
| Parameters | |
|---|---|
@NonNull MenuProvider provider |
the MenuProvider to be added |
| See also | |
|---|---|
removeMenuProvider |
addMenuProvider
public void addMenuProvider(
@NonNull MenuProvider provider,
@NonNull LifecycleOwner owner
)
Adds the given MenuProvider to this MenuHost. This MenuProvider will be removed once the given LifecycleOwner receives an Lifecycle.Event.ON_DESTROY event.
| Parameters | |
|---|---|
@NonNull MenuProvider provider |
the MenuProvider to be added |
@NonNull LifecycleOwner owner |
the Lifecycle owner whose state will determine the removal of the provider |
addMenuProvider
public void addMenuProvider(
@NonNull MenuProvider provider,
@NonNull LifecycleOwner owner,
@NonNull Lifecycle.State state
)
Adds the given MenuProvider to this MenuHost once the given LifecycleOwner reaches the given Lifecycle.State. This MenuProvider will be removed once the given LifecycleOwner goes down from the given Lifecycle.State.
| Parameters | |
|---|---|
@NonNull MenuProvider provider |
the MenuProvider to be added |
@NonNull LifecycleOwner owner |
the Lifecycle owner whose state will be used for automated addition/removal |
@NonNull Lifecycle.State state |
the Lifecycle.State to check for automated addition/removal |
addOnConfigurationChangedListener
public final void addOnConfigurationChangedListener(
@NonNull Consumer<@NonNull Configuration> listener
)
Add a new listener that will get a callback associated with ComponentCallbacks.onConfigurationChanged with the new Configuration.
| Parameters | |
|---|---|
@NonNull Consumer<@NonNull Configuration> listener |
The listener that should be called whenever { |
addOnContextAvailableListener
public final void addOnContextAvailableListener(
@NonNull OnContextAvailableListener listener
)
{@inheritDoc}
Any listener added here will receive a callback as part of super.onCreate(), but importantly before any other logic is done (including calling through to the framework Activity.onCreate) with the exception of restoring the state of the savedStateRegistry for use in your listener.
addOnMultiWindowModeChangedListener
public final void addOnMultiWindowModeChangedListener(
@NonNull Consumer<@NonNull MultiWindowModeChangedInfo> listener
)
Add a new listener that will get a callback associated with Activity.onMultiWindowModeChanged with the new MultiWindowModeChangedInfo.
| Parameters | |
|---|---|
@NonNull Consumer<@NonNull MultiWindowModeChangedInfo> listener |
The listener that should be called whenever Activity#onMultiWindowModeChanged was called. |
addOnNewIntentListener
public final void addOnNewIntentListener(@NonNull Consumer<@NonNull Intent> listener)
Add a new listener that will get a callback associated with Activity.onNewIntent with the new Intent.
addOnPictureInPictureModeChangedListener
public final void addOnPictureInPictureModeChangedListener(
@NonNull Consumer<@NonNull PictureInPictureModeChangedInfo> listener
)
Add a new listener that will get a callback associated with Activity.onPictureInPictureModeChanged with the new PictureInPictureModeChangedInfo.
| Parameters | |
|---|---|
@NonNull Consumer<@NonNull PictureInPictureModeChangedInfo> listener |
The listener that should be called whenever |
addOnPictureInPictureUiStateChangedListener
public final void addOnPictureInPictureUiStateChangedListener(
@NonNull Consumer<@NonNull PictureInPictureUiStateCompat> listener
)
Add a new listener that will get a callback associated with Activity.onPictureInPictureUiStateChanged with the new PictureInPictureUiStateCompat.
| Parameters | |
|---|---|
@NonNull Consumer<@NonNull PictureInPictureUiStateCompat> listener |
The listener that should be called whenever |
addOnTrimMemoryListener
public final void addOnTrimMemoryListener(@NonNull Consumer<@NonNull Integer> listener)
Add a new listener that will get a callback associated with ComponentCallbacks2.onTrimMemory with the int representing the level of trimming.
| Parameters | |
|---|---|
@NonNull Consumer<@NonNull Integer> listener |
The listener that should be called whenever |
addOnUserLeaveHintListener
public final void addOnUserLeaveHintListener(@NonNull Runnable listener)
Add a new listener that will get a callback associated with Activity.onUserLeaveHint
| Parameters | |
|---|---|
@NonNull Runnable listener |
The listener that should be called whenever |
enterPictureInPictureMode
public final void enterPictureInPictureMode(@NonNull PictureInPictureParamsCompat params)
Available since API 24 in the framework Activity class, puts the activity in picture-in-picture mode if possible in the current system state. Any prior calls to setPictureInPictureParams will still apply when entering picture-in-picture through this call.
getActivityResultRegistry
public final @NonNull ActivityResultRegistry getActivityResultRegistry()
Get the ActivityResultRegistry associated with this activity.
| Returns | |
|---|---|
@NonNull ActivityResultRegistry |
getDefaultViewModelCreationExtras
@CallSuper
public @NonNull CreationExtras getDefaultViewModelCreationExtras()
{@inheritDoc}
The extras of getIntent when this is first called will be used as the defaults to any androidx.lifecycle.SavedStateHandle passed to a view model created using this extra.
getDefaultViewModelProviderFactory
public @NonNull ViewModelProvider.Factory getDefaultViewModelProviderFactory()
getFullyDrawnReporter
public @NonNull FullyDrawnReporter getFullyDrawnReporter()
Retrieve the FullyDrawnReporter that should handle the independent parts of the UI that separately report that they are fully drawn.
public ObjectgetLastCustomNonConfigurationInstance()
Return the value previously returned from onRetainCustomNonConfigurationInstance.
getLifecycle
public @NonNull Lifecycle getLifecycle()
{@inheritDoc}
Overriding this method is no longer supported and this method will be made final in a future version of ComponentActivity. If you do override this method, you must:
-
Return an instance of
LifecycleRegistry -
Lazily initialize your LifecycleRegistry object when this is first called.
Note that this method will be called in the super classes' constructor, before any field initialization or object state creation is complete.
getNavigationEventDispatcher
public @NonNull NavigationEventDispatcher getNavigationEventDispatcher()
Lazily provides a NavigationEventDispatcher for back navigation handling, including support for predictive back gestures introduced in Android 13 (API 33+).
This dispatcher acts as the central point for back navigation events. When a navigation event occurs (e.g., a back gesture), it safely invokes ComponentActivity.onBackPressed.
Not stable for override
This property is not intended for override. It is technically open for binary compatibility with previous versions, but overriding this property is unsupported.
getOnBackPressedDispatcher
public final @NonNull OnBackPressedDispatcher getOnBackPressedDispatcher()
Retrieve the OnBackPressedDispatcher that will be triggered when onBackPressed is called.
| Returns | |
|---|---|
@NonNull OnBackPressedDispatcher |
The |
getSavedStateRegistry
public final @NonNull SavedStateRegistry getSavedStateRegistry()
getViewModelStore
public @NonNull ViewModelStore getViewModelStore()
Returns the ViewModelStore associated with this activity
Overriding this method is no longer supported and this method will be made final in a future version of ComponentActivity.
| Returns | |
|---|---|
@NonNull ViewModelStore |
| Throws | |
|---|---|
IllegalStateException |
if called before the Activity is attached to the Application instance i.e., before onCreate() |
initializeViewTreeOwners
@CallSuper
public void initializeViewTreeOwners()
Sets the view tree owners before setting the content view so that the inflation process and attach listeners will see them already present.
invalidateMenu
public void invalidateMenu()
Invalidates the android.view.Menu to ensure that what is displayed matches the current internal state of the menu. This should be called whenever the state of the menu is changed, such as items being removed or disabled based on some user event.
onBackPressed
@MainThread
@CallSuper
public voidonBackPressed()
Called when the activity has detected the user's press of the back key. The onBackPressedDispatcher will be given a chance to handle the back button before the default behavior of Activity.onBackPressed is invoked.
| See also | |
|---|---|
onBackPressedDispatcher |
onConfigurationChanged
@CallSuper
public void onConfigurationChanged(@NonNull Configuration newConfig)
{@inheritDoc}
Dispatches this call to all listeners added via addOnConfigurationChangedListener.
onMultiWindowModeChanged
@CallSuper
public voidonMultiWindowModeChanged(boolean isInMultiWindowMode)
{@inheritDoc}
Dispatches this call to all listeners added via addOnMultiWindowModeChangedListener.
onMultiWindowModeChanged
@RequiresApi(api = 26)
@CallSuper
public void onMultiWindowModeChanged(
boolean isInMultiWindowMode,
@NonNull Configuration newConfig
)
{@inheritDoc}
Dispatches this call to all listeners added via addOnMultiWindowModeChangedListener.
onPictureInPictureModeChanged
@CallSuper
public voidonPictureInPictureModeChanged(boolean isInPictureInPictureMode)
{@inheritDoc}
Dispatches this call to all listeners added via addOnPictureInPictureModeChangedListener.
onPictureInPictureModeChanged
@RequiresApi(api = 26)
@CallSuper
public void onPictureInPictureModeChanged(
boolean isInPictureInPictureMode,
@NonNull Configuration newConfig
)
{@inheritDoc}
Dispatches this call to all listeners added via addOnPictureInPictureModeChangedListener.
onPictureInPictureUiStateChanged
@RequiresApi(api = 31)
@CallSuper
public void onPictureInPictureUiStateChanged(
@NonNull PictureInPictureUiState pipState
)
{@inheritDoc}
@CallSuper
public voidonRequestPermissionsResult(
int requestCode,
@NonNull String[] permissions,
@NonNull int[] grantResults
)
{@inheritDoc}
public ObjectonRetainCustomNonConfigurationInstance()
Use this instead of onRetainNonConfigurationInstance. Retrieve later with lastCustomNonConfigurationInstance.
onRetainNonConfigurationInstance
public final Object onRetainNonConfigurationInstance()
Retain all appropriate non-config state. You can NOT override this yourself! Use a androidx.lifecycle.ViewModel if you want to retain your own non config state.
onTrimMemory
@CallSuper
public void onTrimMemory(int level)
{@inheritDoc}
Dispatches this call to all listeners added via addOnTrimMemoryListener.
peekAvailableContext
public Context peekAvailableContext()
Get the Context if it is currently available. If this returns null, you can use addOnContextAvailableListener to receive a callback for when it available.
| Returns | |
|---|---|
Context |
the Context if it is currently available. |
registerForActivityResult
public final @NonNull ActivityResultLauncher<@NonNull I> <I extends Object, O extends Object> registerForActivityResult(
@NonNull ActivityResultContract<@NonNull I, @NonNull O> contract,
@NonNull ActivityResultCallback<@NonNull O> callback
)
Register a request to start an activity for result, designated by the given contract.
This creates a record in the registry associated with this caller, managing request code, as well as conversions to/from Intent under the hood.
This must be called unconditionally, as part of initialization path, typically as a field initializer of an Activity or Fragment.
| Parameters | |
|---|---|
<I extends Object> |
the type of the input(if any) required to call the activity |
<O extends Object> |
the type of output returned as an activity result |
@NonNull ActivityResultContract<@NonNull I, @NonNull O> contract |
the contract, specifying conversions to/from |
@NonNull ActivityResultCallback<@NonNull O> callback |
the callback to be called on the main thread when activity result is available |
| Returns | |
|---|---|
@NonNull ActivityResultLauncher<@NonNull I> |
the launcher that can be used to start the activity or dispose of the prepared call. |
registerForActivityResult
public final @NonNull ActivityResultLauncher<@NonNull I> <I extends Object, O extends Object> registerForActivityResult(
@NonNull ActivityResultContract<@NonNull I, @NonNull O> contract,
@NonNull ActivityResultRegistry registry,
@NonNull ActivityResultCallback<@NonNull O> callback
)
Register a request to start an activity for result, designated by the given contract.
This creates a record in the given registry, managing request code, as well as conversions to/from Intent under the hood.
This must be called unconditionally, as part of initialization path, typically as a field initializer of an Activity or Fragment.
| Parameters | |
|---|---|
<I extends Object> |
the type of the input(if any) required to call the activity |
<O extends Object> |
the type of output returned as an activity result |
@NonNull ActivityResultContract<@NonNull I, @NonNull O> contract |
the contract, specifying conversions to/from |
@NonNull ActivityResultRegistry registry |
the registry where to hold the record. |
@NonNull ActivityResultCallback<@NonNull O> callback |
the callback to be called on the main thread when activity result is available |
| Returns | |
|---|---|
@NonNull ActivityResultLauncher<@NonNull I> |
the launcher that can be used to start the activity or dispose of the prepared call. |
removeMenuProvider
public void removeMenuProvider(@NonNull MenuProvider provider)
Removes the given MenuProvider from this MenuHost.
| Parameters | |
|---|---|
@NonNull MenuProvider provider |
the MenuProvider to be removed |
removeOnConfigurationChangedListener
public final void removeOnConfigurationChangedListener(
@NonNull Consumer<@NonNull Configuration> listener
)
Remove a previously added listener. It will not receive any future callbacks.
| Parameters | |
|---|---|
@NonNull Consumer<@NonNull Configuration> listener |
The listener previously added with |
removeOnContextAvailableListener
public final void removeOnContextAvailableListener(
@NonNull OnContextAvailableListener listener
)
Remove a OnContextAvailableListener previously added via addOnContextAvailableListener.
| Parameters | |
|---|---|
@NonNull OnContextAvailableListener listener |
The listener that should be removed. |
| See also | |
|---|---|
addOnContextAvailableListener |
removeOnMultiWindowModeChangedListener
public final void removeOnMultiWindowModeChangedListener(
@NonNull Consumer<@NonNull MultiWindowModeChangedInfo> listener
)
Remove a previously added listener. It will not receive any future callbacks.
| Parameters | |
|---|---|
@NonNull Consumer<@NonNull MultiWindowModeChangedInfo> listener |
The listener previously added with |
removeOnNewIntentListener
public final void removeOnNewIntentListener(@NonNull Consumer<@NonNull Intent> listener)
Remove a previously added listener. It will not receive any future callbacks.
| Parameters | |
|---|---|
@NonNull Consumer<@NonNull Intent> listener |
The listener previously added with |
removeOnPictureInPictureModeChangedListener
public final void removeOnPictureInPictureModeChangedListener(
@NonNull Consumer<@NonNull PictureInPictureModeChangedInfo> listener
)
Remove a previously added listener. It will not receive any future callbacks.
| Parameters | |
|---|---|
@NonNull Consumer<@NonNull PictureInPictureModeChangedInfo> listener |
The listener previously added with |
removeOnPictureInPictureUiStateChangedListener
public final void removeOnPictureInPictureUiStateChangedListener(
@NonNull Consumer<@NonNull PictureInPictureUiStateCompat> listener
)
Remove a previously added listener. It will not receive any future callbacks.
| Parameters | |
|---|---|
@NonNull Consumer<@NonNull PictureInPictureUiStateCompat> listener |
The listener previously added with |
removeOnTrimMemoryListener
public final void removeOnTrimMemoryListener(@NonNull Consumer<@NonNull Integer> listener)
Remove a previously added listener. It will not receive any future callbacks.
removeOnUserLeaveHintListener
public final void removeOnUserLeaveHintListener(@NonNull Runnable listener)
Remove a previously added listener. It will not receive any future callbacks.
| Parameters | |
|---|---|
@NonNull Runnable listener |
The listener previously added with |
setPictureInPictureParams
public final void setPictureInPictureParams(@NonNull PictureInPictureParamsCompat params)
Available since API 26 in the framework Activity class, updates the properties of the picture-in-picture activity, or sets it to be used later when enterPictureInPictureMode is called
| Parameters | |
|---|---|
@NonNull PictureInPictureParamsCompat params |
|
public voidstartActivityForResult(
@NonNull Intent intent,
int requestCode,
Bundle options
)
{@inheritDoc}
public voidstartIntentSenderForResult(
@NonNull IntentSender intent,
int requestCode,
Intent fillInIntent,
int flagsMask,
int flagsValues,
int extraFlags
)
{@inheritDoc}
public voidstartIntentSenderForResult(
@NonNull IntentSender intent,
int requestCode,
Intent fillInIntent,
int flagsMask,
int flagsValues,
int extraFlags,
Bundle options
)
{@inheritDoc}
Protected methods
@CallSuper
protected voidonActivityResult(int requestCode, int resultCode, Intent data)
{@inheritDoc}
onCreate
protected void onCreate(Bundle savedInstanceState)
{@inheritDoc}
If your ComponentActivity is annotated with ContentView, this will call setContentView for you.
onNewIntent
@CallSuper
protected void onNewIntent(@NonNull Intent intent)
{@inheritDoc}
Dispatches this call to all listeners added via addOnNewIntentListener.
onUserLeaveHint
@CallSuper
protected void onUserLeaveHint()
{@inheritDoc}
Dispatches this call to all listeners added via addOnUserLeaveHintListener.
Extension functions
ActivityViewModelLazyKt.viewModels
@MainThread
public final @NonNull Lazy<@NonNull VM> <VM extends ViewModel> ActivityViewModelLazyKt.viewModels(
@NonNull ComponentActivity receiver,
Function0<@NonNull CreationExtras> extrasProducer,
Function0<@NonNull ViewModelProvider.Factory> factoryProducer
)
Returns a Lazy delegate to access the ComponentActivity's ViewModel, if factoryProducer is specified then ViewModelProvider.Factory returned by it will be used to create ViewModel first time.
class MyComponentActivity : ComponentActivity() {
val viewmodel: MyViewModel by viewModels()
}
This property can be accessed only after the Activity is attached to the Application, and access prior to that will result in IllegalArgumentException.
AuthenticationUtils.registerForAuthenticationResult
public final @NonNull AuthenticationResultLauncher AuthenticationUtils.registerForAuthenticationResult(
@NonNull ComponentActivity receiver,
@NonNull AuthenticationResultCallback resultCallback
)
Returns an AuthenticationResultLauncher that can be used to initiate authentication.
A success or error result will be delivered to AuthenticationResultCallback.onAuthResult and (one or more) failures will be delivered to AuthenticationResultCallback.onAuthAttemptFailed, which is set by resultCallback. The callback will be executed on the main thread.
This must be called unconditionally, as part of initialization path, typically as a field initializer of an Activity.
Note that if multiple calls to this method are made within a single Fragment or Activity, only the callback registered by the last invocation will be saved and receive authentication results. This can result in unexpected behavior if you intend to manage multiple independent authentication flows. It is strongly recommended to avoid multiple calls to this method in such scenarios.
import androidx.activity.ComponentActivity import androidx.biometric.AuthenticationRequest import androidx.biometric.AuthenticationRequest.Biometric import androidx.biometric.AuthenticationRequest.Companion.biometricRequest import androidx.biometric.AuthenticationResult import androidx.biometric.AuthenticationResultCallback import androidx.biometric.PromptContentItemBulletedText import androidx.biometric.registerForAuthenticationResult class MyActivityForBiometricAuth : ComponentActivity() { val requestAuthentication = registerForAuthenticationResult( object : AuthenticationResultCallback { override fun onAuthResult(result: AuthenticationResult) { when (result) { // Handle successful authentication is AuthenticationResult.Success -> { Log.i(TAG, "onAuthenticationSucceeded with type ${result.authType}") } // Handle authentication error, e.g. user cancellation, lockout errors, // etc is AuthenticationResult.Error -> { Log.i( TAG, "onAuthenticationError " + "with error code: ${result.errorCode} " + "and error string: ${result.errString}", ) } // Handle fallback option clicks is AuthenticationResult.CustomFallbackSelected -> { Log.i(TAG, "fallback is selected, text: ${result.fallback.text}") } } } // Handle intermediate authentication failure, this is optional and // not needed in most cases override fun onAuthAttemptFailed() { Log.i(TAG, "onAuthenticationFailed, try again") } } ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val authRequest = biometricRequest(title = "Title", Biometric.Fallback.DeviceCredential) { setSubtitle("Subtitle") setContent( AuthenticationRequest.BodyContent.VerticalList( "Vertical list description", listOf( PromptContentItemBulletedText("test item1"), PromptContentItemBulletedText("test item2"), ), ) ) setMinStrength(Biometric.Strength.Class3(/*optional: cryptoObject*/ )) setIsConfirmationRequired(true) } Button(this).setOnClickListener { requestAuthentication.launch(authRequest) } } }
| See also | |
|---|---|
registerForAuthenticationResult |
(Executor, AuthenticationResultCallback) |
AuthenticationUtils.registerForAuthenticationResult
public final @NonNull AuthenticationResultLauncher AuthenticationUtils.registerForAuthenticationResult(
@NonNull ComponentActivity receiver,
@NonNull Executor callbackExecutor,
@NonNull AuthenticationResultCallback resultCallback
)
Returns an AuthenticationResultLauncher that can be used to initiate authentication.
A success or error result will be delivered to AuthenticationResultCallback.onAuthResult and (one or more) failures will be delivered to AuthenticationResultCallback.onAuthAttemptFailed, which is set by resultCallback. The callback will be executed on the thread provided by the callbackExecutor.
This must be called unconditionally, as part of initialization path, typically as a field initializer of an Activity.
Note that if multiple calls to this method are made within a single Fragment or Activity, only the callback registered by the last invocation will be saved and receive authentication results. This can result in unexpected behavior if you intend to manage multiple independent authentication flows. It is strongly recommended to avoid multiple calls to this method in such scenarios.
import androidx.activity.ComponentActivity import androidx.biometric.AuthenticationRequest import androidx.biometric.AuthenticationRequest.Biometric import androidx.biometric.AuthenticationRequest.Companion.biometricRequest import androidx.biometric.AuthenticationResult import androidx.biometric.AuthenticationResultCallback import androidx.biometric.PromptContentItemBulletedText import androidx.biometric.registerForAuthenticationResult class MyActivityForBiometricAuth : ComponentActivity() { val requestAuthentication = registerForAuthenticationResult( object : AuthenticationResultCallback { override fun onAuthResult(result: AuthenticationResult) { when (result) { // Handle successful authentication is AuthenticationResult.Success -> { Log.i(TAG, "onAuthenticationSucceeded with type ${result.authType}") } // Handle authentication error, e.g. user cancellation, lockout errors, // etc is AuthenticationResult.Error -> { Log.i( TAG, "onAuthenticationError " + "with error code: ${result.errorCode} " + "and error string: ${result.errString}", ) } // Handle fallback option clicks is AuthenticationResult.CustomFallbackSelected -> { Log.i(TAG, "fallback is selected, text: ${result.fallback.text}") } } } // Handle intermediate authentication failure, this is optional and // not needed in most cases override fun onAuthAttemptFailed() { Log.i(TAG, "onAuthenticationFailed, try again") } } ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val authRequest = biometricRequest(title = "Title", Biometric.Fallback.DeviceCredential) { setSubtitle("Subtitle") setContent( AuthenticationRequest.BodyContent.VerticalList( "Vertical list description", listOf( PromptContentItemBulletedText("test item1"), PromptContentItemBulletedText("test item2"), ), ) ) setMinStrength(Biometric.Strength.Class3(/*optional: cryptoObject*/ )) setIsConfirmationRequired(true) } Button(this).setOnClickListener { requestAuthentication.launch(authRequest) } } }
EdgeToEdge.enableEdgeToEdge
public final void EdgeToEdge.enableEdgeToEdge(
@NonNull ComponentActivity receiver,
@NonNull SystemBarStyle statusBarStyle,
@NonNull SystemBarStyle navigationBarStyle
)
Enables the edge-to-edge display for this ComponentActivity.
To set it up with the default style, call this method in your Activity's onCreate method:
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
...
}The default style configures the system bars with a transparent background when contrast can be enforced by the system (API 29 or above). On older platforms (which only have 3-button/2-button navigation modes), an equivalent scrim is applied to ensure contrast with the system bars.
See SystemBarStyle for more customization options.
| Parameters | |
|---|---|
@NonNull SystemBarStyle statusBarStyle |
The |
@NonNull SystemBarStyle navigationBarStyle |
The |