ComponentActivity


open class ComponentActivity : Activity, LifecycleOwner, ContextAware, ViewModelStoreOwner, HasDefaultViewModelProviderFactory, SavedStateRegistryOwner, OnBackPressedDispatcherOwner, NavigationEventDispatcherOwner, ActivityResultRegistryOwner, ActivityResultCaller, OnConfigurationChangedProvider, OnTrimMemoryProvider, OnNewIntentProvider, OnMultiWindowModeChangedProvider, PictureInPictureProvider, MenuHost, FullyDrawnReporterOwner

Known direct subclasses
FragmentActivity

Base class for activities that want to use the support-based Fragments.

PreviewActivity

Activity used to run @Composable previews from Android Studio.

Known indirect subclasses
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

Alternate constructor that can be used to provide a default layout that will be inflated as part of super.onCreate(savedInstanceState).

Public functions

open Unit
open Unit

Adds the given MenuProvider to this MenuHost.

open Unit

Adds the given MenuProvider to this MenuHost.

open Unit
addMenuProvider(
    provider: MenuProvider,
    owner: LifecycleOwner,
    state: Lifecycle.State
)

Adds the given MenuProvider to this MenuHost once the given LifecycleOwner reaches the given Lifecycle.State.

final Unit

Add a new listener that will get a callback associated with ComponentCallbacks.onConfigurationChanged with the new Configuration.

final Unit

{@inheritDoc}

final Unit

Add a new listener that will get a callback associated with Activity.onMultiWindowModeChanged with the new MultiWindowModeChangedInfo.

final Unit

Add a new listener that will get a callback associated with Activity.onNewIntent with the new Intent.

final Unit

Add a new listener that will get a callback associated with Activity.onPictureInPictureModeChanged with the new PictureInPictureModeChangedInfo.

final Unit

Add a new listener that will get a callback associated with Activity.onPictureInPictureUiStateChanged with the new PictureInPictureUiStateCompat.

final Unit

Add a new listener that will get a callback associated with ComponentCallbacks2.onTrimMemory with the int representing the level of trimming.

final Unit

Add a new listener that will get a callback associated with Activity.onUserLeaveHint

final Unit

Available since API 24 in the framework Activity class, puts the activity in picture-in-picture mode if possible in the current system state.

open Unit

Sets the view tree owners before setting the content view so that the inflation process and attach listeners will see them already present.

open Unit

Invalidates the android.view.Menu to ensure that what is displayed matches the current internal state of the menu.

open Unit

This function is deprecated. This method has been deprecated in favor of using the {@link OnBackPressedDispatcher} via {@link #getOnBackPressedDispatcher()}.

open Unit

{@inheritDoc}

open Boolean
onCreatePanelMenu(featureId: Int, menu: Menu)
open Boolean
onMenuItemSelected(featureId: Int, item: MenuItem)
open Unit

This function is deprecated. Deprecated in android.app.Activity

open Unit
@RequiresApi(api = 26)
@CallSuper
onMultiWindowModeChanged(
    isInMultiWindowMode: Boolean,
    newConfig: Configuration
)

{@inheritDoc}

open Unit
onPanelClosed(featureId: Int, menu: Menu)
open Unit
@CallSuper
onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean)

This function is deprecated. Deprecated in android.app.Activity

open Unit
@RequiresApi(api = 26)
@CallSuper
onPictureInPictureModeChanged(
    isInPictureInPictureMode: Boolean,
    newConfig: Configuration
)

{@inheritDoc}

open Unit

{@inheritDoc}

open Boolean
onPreparePanel(featureId: Int, view: View?, menu: Menu)
open Unit
@CallSuper
onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<String>,
    grantResults: IntArray
)

This function 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.

open Any?

This function is deprecated. Use a {@link androidx.lifecycle.ViewModel} to store non config state.

final Any?

Retain all appropriate non-config state.

open Unit

{@inheritDoc}

open Context?

Get the Context if it is currently available.

final ActivityResultLauncher<I>
<I : Any?, O : Any?> registerForActivityResult(
    contract: ActivityResultContract<I, O>,
    callback: ActivityResultCallback<O>
)

Register a request to start an activity for result, designated by the given contract.

final ActivityResultLauncher<I>
<I : Any?, O : Any?> registerForActivityResult(
    contract: ActivityResultContract<I, O>,
    registry: ActivityResultRegistry,
    callback: ActivityResultCallback<O>
)

Register a request to start an activity for result, designated by the given contract.

open Unit

Removes the given MenuProvider from this MenuHost.

final Unit

Remove a previously added listener.

final Unit

Remove a OnContextAvailableListener previously added via addOnContextAvailableListener.

final Unit

Remove a previously added listener.

final Unit

Remove a previously added listener.

final Unit

Remove a previously added listener.

final Unit

Remove a previously added listener.

final Unit

Remove a previously added listener.

final Unit

Remove a previously added listener.

open Unit
open Unit
setContentView(layoutResID: @LayoutRes Int)
open Unit
open Unit
final Unit

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

open Unit
startActivityForResult(intent: Intent, requestCode: Int)

This function 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.

open Unit
startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?)

This function 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.

open Unit
startIntentSenderForResult(
    intent: IntentSender,
    requestCode: Int,
    fillInIntent: Intent?,
    flagsMask: Int,
    flagsValues: Int,
    extraFlags: Int
)

This function 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.

open Unit
startIntentSenderForResult(
    intent: IntentSender,
    requestCode: Int,
    fillInIntent: Intent?,
    flagsMask: Int,
    flagsValues: Int,
    extraFlags: Int,
    options: Bundle?
)

This function 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 functions

open Unit
@CallSuper
onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)

This function 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.

open Unit
onCreate(savedInstanceState: Bundle?)

{@inheritDoc}

open Unit

{@inheritDoc}

open Unit
open Unit

{@inheritDoc}

Public properties

final ActivityResultRegistry

Get the ActivityResultRegistry associated with this activity.

open CreationExtras
open ViewModelProvider.Factory
open FullyDrawnReporter

Retrieve the FullyDrawnReporter that should handle the independent parts of the UI that separately report that they are fully drawn.

open Any?
open Lifecycle

{@inheritDoc}

open NavigationEventDispatcher

Lazily provides a NavigationEventDispatcher for back navigation handling, including support for predictive back gestures introduced in Android 13 (API 33+).

final OnBackPressedDispatcher

Retrieve the OnBackPressedDispatcher that will be triggered when onBackPressed is called.

final SavedStateRegistry
open ViewModelStore

Extension functions

suspend SpaceRequestResult

Request that the system places the application into full space mode.

suspend SpaceRequestResult

Request that the system places the application into home space mode.

inline Lazy<VM>
@MainThread
<VM : ViewModel> ComponentActivity.viewModels(
    noinline extrasProducer: (() -> CreationExtras)?,
    noinline factoryProducer: (() -> ViewModelProvider.Factory)?
)

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.

AuthenticationResultLauncher

Returns an AuthenticationResultLauncher that can be used to initiate authentication.

AuthenticationResultLauncher
ComponentActivity.registerForAuthenticationResult(
    callbackExecutor: Executor,
    resultCallback: AuthenticationResultCallback
)

Returns an AuthenticationResultLauncher that can be used to initiate authentication.

Unit
ComponentActivity.setContent(
    parent: CompositionContext?,
    content: @Composable () -> Unit
)

Composes the given composable into the given activity.

Unit
ComponentActivity.enableEdgeToEdge(
    statusBarStyle: SystemBarStyle,
    navigationBarStyle: SystemBarStyle
)

Enables the edge-to-edge display for this ComponentActivity.

Inherited functions

From android.app.Activity
Unit
Unit
Unit
Unit
PendingIntent
createPendingResult(requestCode: Int, data: Intent, flags: Int)
Unit
Unit
Boolean
Boolean
Boolean
Boolean
Unit
dump(
    prefix: String,
    fd: FileDescriptor?,
    writer: PrintWriter,
    args: Array<String>?
)
Unit
Boolean
T
<T : View> findViewById(id: Int)
Unit
Unit
finishActivity(requestCode: Int)
Unit
finishActivityFromChild(child: Activity, requestCode: Int)
Unit
Unit
Unit
Unit
SharedPreferences
Any
Boolean
Unit
Cursor
managedQuery(
    uri: Uri,
    projection: Array<String>,
    selection: String,
    selectionArgs: Array<String>,
    sortOrder: String
)
Boolean
Boolean
navigateUpTo(upIntent: Intent)
Boolean
navigateUpToFromChild(child: Activity, upIntent: Intent)
Unit
Unit
Unit
onActivityReenter(resultCode: Int, data: Intent)
Unit
onActivityResult(
    requestCode: Int,
    resultCode: Int,
    data: Intent?,
    caller: ComponentCaller
)
Unit
onApplyThemeResource(theme: Resources.Theme, resid: Int, first: Boolean)
Unit
Unit
Unit
onChildTitleChanged(childActivity: Activity, title: CharSequence)
Unit
Boolean
Unit
Unit
onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?)
Unit
onCreateContextMenu(
    menu: ContextMenu,
    v: View,
    menuInfo: ContextMenu.ContextMenuInfo
)
CharSequence?
Dialog
Dialog?
onCreateDialog(id: Int, args: Bundle)
Unit
Boolean
View?
onCreatePanelView(featureId: Int)
Boolean
onCreateThumbnail(outBitmap: Bitmap, canvas: Canvas)
View?
onCreateView(name: String, context: Context, attrs: AttributeSet)
View?
onCreateView(
    parent: View?,
    name: String,
    context: Context,
    attrs: AttributeSet
)
Unit
Unit
Unit
Boolean
Unit
onGetDirectActions(
    cancellationSignal: CancellationSignal,
    callback: Consumer<MutableList<DirectAction>>
)
HandoffActivityData?
Boolean
onKeyDown(keyCode: Int, event: KeyEvent)
Boolean
onKeyLongPress(keyCode: Int, event: KeyEvent)
Boolean
onKeyMultiple(keyCode: Int, repeatCount: Int, event: KeyEvent)
Boolean
onKeyShortcut(keyCode: Int, event: KeyEvent)
Boolean
onKeyUp(keyCode: Int, event: KeyEvent)
Unit
Unit
Unit
Boolean
onMenuOpened(featureId: Int, menu: Menu)
Boolean
Boolean
Unit
onNewIntent(intent: Intent, caller: ComponentCaller)
Boolean
Unit
Unit
Unit
onPerformDirectAction(
    actionId: String,
    arguments: Bundle,
    cancellationSignal: CancellationSignal,
    resultListener: Consumer<Bundle>
)
Boolean
Unit
onPostCreate(savedInstanceState: Bundle?)
Unit
onPostCreate(
    savedInstanceState: Bundle?,
    persistentState: PersistableBundle?
)
Unit
Unit
onPrepareDialog(id: Int, dialog: Dialog)
Unit
onPrepareDialog(id: Int, dialog: Dialog, args: Bundle)
Unit
Boolean
Unit
Unit
Unit
onProvideKeyboardShortcuts(
    data: MutableList<KeyboardShortcutGroup>,
    menu: Menu?,
    deviceId: Int
)
Uri
Unit
onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<String>,
    grantResults: IntArray,
    deviceId: Int
)
Unit
Unit
onRestoreInstanceState(savedInstanceState: Bundle)
Unit
onRestoreInstanceState(
    savedInstanceState: Bundle?,
    persistentState: PersistableBundle?
)
Unit
Unit
onSaveInstanceState(
    outState: Bundle,
    outPersistentState: PersistableBundle
)
Boolean
Boolean
Unit
Unit
Unit
Unit
onTitleChanged(title: CharSequence, color: Int)
Unit
onTopResumedActivityChanged(isTopResumedActivity: Boolean)
Boolean
Boolean
Unit
Unit
Unit
Unit
ActionMode?
ActionMode?
Unit
Unit
Unit
overrideActivityTransition(
    overrideType: Int,
    enterAnim: Int,
    exitAnim: Int
)
Unit
overrideActivityTransition(
    overrideType: Int,
    enterAnim: Int,
    exitAnim: Int,
    backgroundColor: Int
)
Unit
overridePendingTransition(enterAnim: Int, exitAnim: Int)
Unit
overridePendingTransition(
    enterAnim: Int,
    exitAnim: Int,
    backgroundColor: Int
)
Unit
Unit
Unit
Unit
Unit
Unit
Boolean
Unit
DragAndDropPermissions
Unit
requestFullscreenMode(
    request: Int,
    approvalCallback: OutcomeReceiver<VoidThrowable>?
)
Unit
Unit
requestPermissions(permissions: Array<String>, requestCode: Int)
Unit
requestPermissions(
    permissions: Array<String>,
    requestCode: Int,
    deviceId: Int
)
Unit
Boolean
Boolean
T
<T : View> requireViewById(id: Int)
Unit
Unit
setActionBar(toolbar: Toolbar?)
Unit
Unit
Unit
Unit
Unit
setFeatureDrawable(featureId: Int, drawable: Drawable)
Unit
setFeatureDrawableAlpha(featureId: Int, alpha: Int)
Unit
setFeatureDrawableResource(featureId: Int, resId: Int)
Unit
setFeatureDrawableUri(featureId: Int, uri: Uri)
Unit
Unit
setHandoffEnabled(
    handoffEnabled: Boolean,
    handoffActivityParams: HandoffActivityParams?
)
Unit
setInheritShowWhenLocked(inheritShowWhenLocked: Boolean)
Unit
setIntent(newIntent: Intent?, newCaller: ComponentCaller?)
Unit
setLocusContext(locusId: LocusId?, bundle: Bundle?)
Unit
Unit
setProgress(progress: Int)
Unit
Unit
Unit
Unit
Unit
setResult(resultCode: Int)
Unit
setResult(resultCode: Int, data: Intent)
Unit
setSecondaryProgress(secondaryProgress: Int)
Unit
setShouldDockBigOverlays(shouldDockBigOverlays: Boolean)
Unit
setShowWhenLocked(showWhenLocked: Boolean)
Unit
Unit
setTheme(resid: Int)
Unit
setTitle(titleId: Int)
Boolean
setTranslucent(translucent: Boolean)
Unit
setTurnScreenOn(turnScreenOn: Boolean)
Unit
setVisible(visible: Boolean)
Unit
setVrModeEnabled(enabled: Boolean, requestedComponent: ComponentName)
Boolean
Boolean
Boolean
Boolean
Boolean
Unit
Boolean
showDialog(id: Int, args: Bundle)
Unit
ActionMode?
ActionMode?
Unit
Unit
startActivities(intents: Array<Intent>, options: Bundle?)
Unit
Unit
startActivity(intent: Intent, options: Bundle?)
Unit
startActivityFromChild(child: Activity, intent: Intent, requestCode: Int)
Unit
startActivityFromChild(
    child: Activity,
    intent: Intent,
    requestCode: Int,
    options: Bundle?
)
Unit
startActivityFromFragment(
    fragment: Fragment,
    intent: Intent,
    requestCode: Int
)
Unit
startActivityFromFragment(
    fragment: Fragment,
    intent: Intent,
    requestCode: Int,
    options: Bundle?
)
Boolean
startActivityIfNeeded(intent: Intent, requestCode: Int)
Boolean
startActivityIfNeeded(intent: Intent, requestCode: Int, options: Bundle?)
Unit
startIntentSender(
    intent: IntentSender,
    fillInIntent: Intent?,
    flagsMask: Int,
    flagsValues: Int,
    extraFlags: Int
)
Unit
startIntentSender(
    intent: IntentSender,
    fillInIntent: Intent?,
    flagsMask: Int,
    flagsValues: Int,
    extraFlags: Int,
    options: Bundle?
)
Unit
startIntentSenderFromChild(
    child: Activity,
    intent: IntentSender,
    requestCode: Int,
    fillInIntent: Intent,
    flagsMask: Int,
    flagsValues: Int,
    extraFlags: Int
)
Unit
startIntentSenderFromChild(
    child: Activity,
    intent: IntentSender,
    requestCode: Int,
    fillInIntent: Intent,
    flagsMask: Int,
    flagsValues: Int,
    extraFlags: Int,
    options: Bundle?
)
Unit
Unit
Unit
Boolean
Boolean
startNextMatchingActivity(intent: Intent, options: Bundle?)
Unit
Unit
startSearch(
    initialQuery: String?,
    selectInitialQuery: Boolean,
    appSearchData: Bundle?,
    globalSearch: Boolean
)
Unit
Unit
Unit
Unit
Unit
triggerSearch(query: String, appSearchData: Bundle?)
Unit
Unit
Unit
Unit
From android.content.Context
Boolean
bindIsolatedService(
    service: Intent,
    flags: Context.BindServiceFlags,
    instanceName: String,
    executor: Executor,
    conn: ServiceConnection
)
Int
ColorStateList
Drawable?
String
getString(resId: Int)
String
getString(resId: Int, vararg formatArgs: Any)
T
<T : Any> getSystemService(serviceClass: Class<T>)
CharSequence
getText(resId: Int)
TypedArray
TypedArray
TypedArray
TypedArray
obtainStyledAttributes(
    set: AttributeSet?,
    attrs: IntArray,
    defStyleAttr: Int,
    defStyleRes: Int
)
Unit
Unit
sendBroadcastWithMultiplePermissions(
    intent: Intent,
    receiverPermissions: Array<String>
)
From android.view.ContextThemeWrapper
Unit
applyOverrideConfiguration(overrideConfiguration: Configuration)
From android.content.ContextWrapper
Boolean
bindIsolatedService(
    service: Intent,
    flags: Int,
    instanceName: String,
    executor: Executor,
    conn: ServiceConnection
)
Boolean
bindService(
    service: Intent,
    conn: ServiceConnection,
    flags: Context.BindServiceFlags
)
Boolean
bindService(service: Intent, conn: ServiceConnection, flags: Int)
Boolean
bindService(
    service: Intent,
    flags: Context.BindServiceFlags,
    executor: Executor,
    conn: ServiceConnection
)
Boolean
bindService(
    service: Intent,
    flags: Int,
    executor: Executor,
    conn: ServiceConnection
)
Boolean
bindServiceAsUser(
    service: Intent,
    conn: ServiceConnection,
    flags: Context.BindServiceFlags,
    user: UserHandle
)
Boolean
bindServiceAsUser(
    service: Intent,
    conn: ServiceConnection,
    flags: Int,
    user: UserHandle
)
Int
Int
IntArray
Int
Int
checkCallingUriPermission(uri: Uri, modeFlags: Int)
IntArray
Int
checkContentUriPermissionFull(uri: Uri, pid: Int, uid: Int, modeFlags: Int)
Int
checkPermission(permission: String, pid: Int, uid: Int)
Int
Int
checkUriPermission(uri: Uri, pid: Int, uid: Int, modeFlags: Int)
Int
checkUriPermission(
    uri: Uri?,
    readPermission: String?,
    writePermission: String?,
    pid: Int,
    uid: Int,
    modeFlags: Int
)
IntArray
checkUriPermissions(
    uris: MutableList<Uri>,
    pid: Int,
    uid: Int,
    modeFlags: Int
)
Unit
Context
createAttributionContext(attributionTag: String?)
Context
createConfigurationContext(overrideConfiguration: Configuration)
Context
createContext(contextParams: ContextParams)
Context
Context
Context
Context
Context
createPackageContext(packageName: String, flags: Int)
Context
createWindowContext(type: Int, options: Bundle?)
Context
createWindowContext(display: Display, type: Int, options: Bundle?)
Array<String>
Boolean
Boolean
Boolean
Unit
enforceCallingOrSelfPermission(permission: String, message: String?)
Unit
enforceCallingOrSelfUriPermission(
    uri: Uri,
    modeFlags: Int,
    message: String
)
Unit
enforceCallingPermission(permission: String, message: String?)
Unit
enforceCallingUriPermission(uri: Uri, modeFlags: Int, message: String)
Unit
enforcePermission(permission: String, pid: Int, uid: Int, message: String?)
Unit
enforceUriPermission(
    uri: Uri,
    pid: Int,
    uid: Int,
    modeFlags: Int,
    message: String
)
Unit
enforceUriPermission(
    uri: Uri?,
    readPermission: String?,
    writePermission: String?,
    pid: Int,
    uid: Int,
    modeFlags: Int,
    message: String?
)
Array<String>
File
File
getDir(name: String, mode: Int)
File?
Array<File>
File
SharedPreferences
String?
getSystemServiceName(serviceClass: Class<*>)
Unit
grantUriPermission(toPackage: String, uri: Uri, modeFlags: Int)
Boolean
moveDatabaseFrom(sourceContext: Context, name: String)
Boolean
moveSharedPreferencesFrom(sourceContext: Context, name: String)
FileInputStream
FileOutputStream
openFileOutput(name: String, mode: Int)
SQLiteDatabase
openOrCreateDatabase(
    name: String,
    mode: Int,
    factory: SQLiteDatabase.CursorFactory
)
SQLiteDatabase
openOrCreateDatabase(
    name: String,
    mode: Int,
    factory: SQLiteDatabase.CursorFactory,
    errorHandler: DatabaseErrorHandler?
)
Drawable
Unit
Unit
Intent?
Intent?
registerReceiver(
    receiver: BroadcastReceiver?,
    filter: IntentFilter,
    flags: Int
)
Intent?
registerReceiver(
    receiver: BroadcastReceiver?,
    filter: IntentFilter,
    broadcastPermission: String?,
    scheduler: Handler?
)
Intent?
registerReceiver(
    receiver: BroadcastReceiver?,
    filter: IntentFilter,
    broadcastPermission: String?,
    scheduler: Handler?,
    flags: Int
)
Unit
Unit
Unit
Unit
revokeUriPermission(uri: Uri, modeFlags: Int)
Unit
revokeUriPermission(targetPackage: String, uri: Uri, modeFlags: Int)
Unit
Unit
sendBroadcast(intent: Intent, receiverPermission: String?)
Unit
sendBroadcast(intent: Intent, receiverPermission: String?, options: Bundle?)
Unit
Unit
sendBroadcastAsUser(
    intent: Intent,
    user: UserHandle,
    receiverPermission: String?
)
Unit
sendOrderedBroadcast(intent: Intent, receiverPermission: String?)
Unit
sendOrderedBroadcast(
    intent: Intent,
    receiverPermission: String?,
    options: Bundle?
)
Unit
sendOrderedBroadcast(
    intent: Intent,
    receiverPermission: String?,
    resultReceiver: BroadcastReceiver?,
    scheduler: Handler?,
    initialCode: Int,
    initialData: String?,
    initialExtras: Bundle?
)
Unit
sendOrderedBroadcast(
    intent: Intent,
    receiverPermission: String?,
    options: Bundle?,
    resultReceiver: BroadcastReceiver?,
    scheduler: Handler?,
    initialCode: Int,
    initialData: String?,
    initialExtras: Bundle?
)
Unit
sendOrderedBroadcast(
    intent: Intent,
    receiverPermission: String?,
    receiverAppOp: String?,
    resultReceiver: BroadcastReceiver?,
    scheduler: Handler?,
    initialCode: Int,
    initialData: String?,
    initialExtras: Bundle?
)
Unit
sendOrderedBroadcast(
    intent: Intent,
    initialCode: Int,
    receiverPermission: String?,
    receiverAppOp: String?,
    resultReceiver: BroadcastReceiver?,
    scheduler: Handler?,
    initialData: String?,
    initialExtras: Bundle?,
    options: Bundle?
)
Unit
sendOrderedBroadcastAsUser(
    intent: Intent,
    user: UserHandle,
    receiverPermission: String?,
    resultReceiver: BroadcastReceiver?,
    scheduler: Handler?,
    initialCode: Int,
    initialData: String?,
    initialExtras: Bundle?
)
Unit
Unit
sendStickyBroadcast(intent: Intent, options: Bundle?)
Unit
Unit
sendStickyOrderedBroadcast(
    intent: Intent,
    resultReceiver: BroadcastReceiver?,
    scheduler: Handler?,
    initialCode: Int,
    initialData: String?,
    initialExtras: Bundle?
)
Unit
sendStickyOrderedBroadcastAsUser(
    intent: Intent,
    user: UserHandle,
    resultReceiver: BroadcastReceiver?,
    scheduler: Handler?,
    initialCode: Int,
    initialData: String?,
    initialExtras: Bundle?
)
Unit
Unit
ComponentName?
Boolean
startInstrumentation(
    className: ComponentName,
    profileFile: String?,
    arguments: Bundle?
)
ComponentName?
startService(service: Intent)
Boolean
Unit
Unit
Unit
Unit
Unit
updateServiceGroup(conn: ServiceConnection, group: Int, importance: Int)
From android.view.Window.Callback

Inherited properties

From android.app.Activity
open ActionBar?
Application
open ComponentCaller?
open ComponentName?
open String?
open Int
open ComponentName
open Scene
open TransitionManager
open ComponentCaller
open View?
open FragmentManager
open ComponentCaller
open Intent
open Boolean
open Boolean
Boolean
open Boolean
open Boolean
Boolean
open Boolean
open Boolean
open Boolean
open Boolean
open Boolean
open Boolean
open Boolean
open Boolean
open Any?
open String?
open Int
open LayoutInflater
open LoaderManager
open String
open Int
MediaController
open MenuInflater
open OnBackInvokedDispatcher
Activity
open Intent?
open Uri?
open Int
SearchEvent
SplashScreen
open Int
CharSequence
Int
open VoiceInteractor
Int
open Window
open WindowManager
From android.content.Context
From android.view.ContextThemeWrapper
From android.content.ContextWrapper

Public constructors

ComponentActivity

Added in 1.0.0
ComponentActivity()

ComponentActivity

Added in 1.0.0
@ContentView
ComponentActivity(contentLayoutId: @LayoutRes Int)

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 functions

addContentView

open fun addContentView(view: View?, params: ViewGroup.LayoutParams?): Unit

addMenuProvider

Added in 1.4.0
open fun addMenuProvider(provider: MenuProvider): Unit

Adds the given MenuProvider to this MenuHost. If using this method, you must manually remove the provider when necessary.

Parameters
provider: MenuProvider

the MenuProvider to be added

addMenuProvider

Added in 1.4.0
open fun addMenuProvider(provider: MenuProvider, owner: LifecycleOwner): Unit

Adds the given MenuProvider to this MenuHost. This MenuProvider will be removed once the given LifecycleOwner receives an Lifecycle.Event.ON_DESTROY event.

Parameters
provider: MenuProvider

the MenuProvider to be added

owner: LifecycleOwner

the Lifecycle owner whose state will determine the removal of the provider

addMenuProvider

Added in 1.4.0
open fun addMenuProvider(
    provider: MenuProvider,
    owner: LifecycleOwner,
    state: Lifecycle.State
): Unit

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
provider: MenuProvider

the MenuProvider to be added

owner: LifecycleOwner

the Lifecycle owner whose state will be used for automated addition/removal

state: Lifecycle.State

the Lifecycle.State to check for automated addition/removal

addOnConfigurationChangedListener

Added in 1.5.0
final fun addOnConfigurationChangedListener(listener: Consumer<Configuration>): Unit

Add a new listener that will get a callback associated with ComponentCallbacks.onConfigurationChanged with the new Configuration.

Parameters
listener: Consumer<Configuration>

The listener that should be called whenever {ComponentCallbacks.onConfigurationChanged was called.

addOnContextAvailableListener

final fun addOnContextAvailableListener(listener: OnContextAvailableListener): Unit

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

Added in 1.5.0
final fun addOnMultiWindowModeChangedListener(
    listener: Consumer<MultiWindowModeChangedInfo>
): Unit

Add a new listener that will get a callback associated with Activity.onMultiWindowModeChanged with the new MultiWindowModeChangedInfo.

Parameters
listener: Consumer<MultiWindowModeChangedInfo>

The listener that should be called whenever Activity#onMultiWindowModeChanged was called.

addOnNewIntentListener

Added in 1.5.0
final fun addOnNewIntentListener(listener: Consumer<Intent>): Unit

Add a new listener that will get a callback associated with Activity.onNewIntent with the new Intent.

Parameters
listener: Consumer<Intent>

The listener that should be called whenever android.app.Activity#onNewIntent was called.

addOnPictureInPictureModeChangedListener

Added in 1.5.0
final fun addOnPictureInPictureModeChangedListener(
    listener: Consumer<PictureInPictureModeChangedInfo>
): Unit

Add a new listener that will get a callback associated with Activity.onPictureInPictureModeChanged with the new PictureInPictureModeChangedInfo.

Parameters
listener: Consumer<PictureInPictureModeChangedInfo>

The listener that should be called whenever Activity.onPictureInPictureModeChanged was called.

addOnPictureInPictureUiStateChangedListener

Added in 1.13.0
final fun addOnPictureInPictureUiStateChangedListener(
    listener: Consumer<PictureInPictureUiStateCompat>
): Unit

Add a new listener that will get a callback associated with Activity.onPictureInPictureUiStateChanged with the new PictureInPictureUiStateCompat.

Parameters
listener: Consumer<PictureInPictureUiStateCompat>

The listener that should be called whenever Activity.onPictureInPictureUiStateChanged was called.

addOnTrimMemoryListener

Added in 1.5.0
final fun addOnTrimMemoryListener(listener: Consumer<Int>): Unit

Add a new listener that will get a callback associated with ComponentCallbacks2.onTrimMemory with the int representing the level of trimming.

Parameters
listener: Consumer<Int>

The listener that should be called whenever ComponentCallbacks2.onTrimMemory was called.

addOnUserLeaveHintListener

Added in 1.9.0
final fun addOnUserLeaveHintListener(listener: Runnable): Unit

Add a new listener that will get a callback associated with Activity.onUserLeaveHint

Parameters
listener: Runnable

The listener that should be called whenever Activity.onUserLeaveHint was called.

enterPictureInPictureMode

Added in 1.13.0
final fun enterPictureInPictureMode(params: PictureInPictureParamsCompat): Unit

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.

initializeViewTreeOwners

Added in 1.8.0
@CallSuper
open fun initializeViewTreeOwners(): Unit

Sets the view tree owners before setting the content view so that the inflation process and attach listeners will see them already present.

invalidateMenu

Added in 1.4.0
open fun invalidateMenu(): Unit

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

Added in 1.6.0
@MainThread
@CallSuper
open fun onBackPressed(): Unit

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.

onConfigurationChanged

@CallSuper
open fun onConfigurationChanged(newConfig: Configuration): Unit

{@inheritDoc}

Dispatches this call to all listeners added via addOnConfigurationChangedListener.

onCreatePanelMenu

open fun onCreatePanelMenu(featureId: Int, menu: Menu): Boolean

onMenuItemSelected

open fun onMenuItemSelected(featureId: Int, item: MenuItem): Boolean

onMultiWindowModeChanged

Added in 1.5.0
@CallSuper
open fun onMultiWindowModeChanged(isInMultiWindowMode: Boolean): Unit

{@inheritDoc}

Dispatches this call to all listeners added via addOnMultiWindowModeChangedListener.

onMultiWindowModeChanged

@RequiresApi(api = 26)
@CallSuper
open fun onMultiWindowModeChanged(
    isInMultiWindowMode: Boolean,
    newConfig: Configuration
): Unit

{@inheritDoc}

Dispatches this call to all listeners added via addOnMultiWindowModeChangedListener.

onPanelClosed

open fun onPanelClosed(featureId: Int, menu: Menu): Unit

onPictureInPictureModeChanged

Added in 1.5.0
@CallSuper
open fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean): Unit

{@inheritDoc}

Dispatches this call to all listeners added via addOnPictureInPictureModeChangedListener.

onPictureInPictureModeChanged

@RequiresApi(api = 26)
@CallSuper
open fun onPictureInPictureModeChanged(
    isInPictureInPictureMode: Boolean,
    newConfig: Configuration
): Unit

{@inheritDoc}

Dispatches this call to all listeners added via addOnPictureInPictureModeChangedListener.

onPictureInPictureUiStateChanged

@RequiresApi(api = 31)
@CallSuper
open fun onPictureInPictureUiStateChanged(pipState: PictureInPictureUiState): Unit

{@inheritDoc}

onPreparePanel

open fun onPreparePanel(featureId: Int, view: View?, menu: Menu): Boolean

onRequestPermissionsResult

Added in 1.2.0
Deprecated in 1.2.0
@CallSuper
open fun onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<String>,
    grantResults: IntArray
): Unit

{@inheritDoc}

onRetainCustomNonConfigurationInstance

Added in 1.0.0
Deprecated in 1.0.0
open fun onRetainCustomNonConfigurationInstance(): Any?

Use this instead of onRetainNonConfigurationInstance. Retrieve later with lastCustomNonConfigurationInstance.

onRetainNonConfigurationInstance

Added in 1.0.0
final fun onRetainNonConfigurationInstance(): Any?

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
open fun onTrimMemory(level: Int): Unit

{@inheritDoc}

Dispatches this call to all listeners added via addOnTrimMemoryListener.

peekAvailableContext

open fun peekAvailableContext(): Context?

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

final fun <I : Any?, O : Any?> registerForActivityResult(
    contract: ActivityResultContract<I, O>,
    callback: ActivityResultCallback<O>
): ActivityResultLauncher<I>

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 : Any?>

the type of the input(if any) required to call the activity

<O : Any?>

the type of output returned as an activity result

contract: ActivityResultContract<I, O>

the contract, specifying conversions to/from Intents

callback: ActivityResultCallback<O>

the callback to be called on the main thread when activity result is available

Returns
ActivityResultLauncher<I>

the launcher that can be used to start the activity or dispose of the prepared call.

registerForActivityResult

final fun <I : Any?, O : Any?> registerForActivityResult(
    contract: ActivityResultContract<I, O>,
    registry: ActivityResultRegistry,
    callback: ActivityResultCallback<O>
): ActivityResultLauncher<I>

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 : Any?>

the type of the input(if any) required to call the activity

<O : Any?>

the type of output returned as an activity result

contract: ActivityResultContract<I, O>

the contract, specifying conversions to/from Intents

registry: ActivityResultRegistry

the registry where to hold the record.

callback: ActivityResultCallback<O>

the callback to be called on the main thread when activity result is available

Returns
ActivityResultLauncher<I>

the launcher that can be used to start the activity or dispose of the prepared call.

removeMenuProvider

Added in 1.4.0
open fun removeMenuProvider(provider: MenuProvider): Unit

Removes the given MenuProvider from this MenuHost.

Parameters
provider: MenuProvider

the MenuProvider to be removed

removeOnConfigurationChangedListener

Added in 1.5.0
final fun removeOnConfigurationChangedListener(listener: Consumer<Configuration>): Unit

Remove a previously added listener. It will not receive any future callbacks.

Parameters
listener: Consumer<Configuration>

The listener previously added with addOnConfigurationChangedListener that should be removed.

removeOnContextAvailableListener

final fun removeOnContextAvailableListener(listener: OnContextAvailableListener): Unit

Remove a OnContextAvailableListener previously added via addOnContextAvailableListener.

Parameters
listener: OnContextAvailableListener

The listener that should be removed.

removeOnMultiWindowModeChangedListener

Added in 1.5.0
final fun removeOnMultiWindowModeChangedListener(
    listener: Consumer<MultiWindowModeChangedInfo>
): Unit

Remove a previously added listener. It will not receive any future callbacks.

Parameters
listener: Consumer<MultiWindowModeChangedInfo>

The listener previously added with addOnMultiWindowModeChangedListener that should be removed.

removeOnNewIntentListener

Added in 1.5.0
final fun removeOnNewIntentListener(listener: Consumer<Intent>): Unit

Remove a previously added listener. It will not receive any future callbacks.

Parameters
listener: Consumer<Intent>

The listener previously added with addOnNewIntentListener that should be removed.

removeOnPictureInPictureModeChangedListener

Added in 1.5.0
final fun removeOnPictureInPictureModeChangedListener(
    listener: Consumer<PictureInPictureModeChangedInfo>
): Unit

Remove a previously added listener. It will not receive any future callbacks.

Parameters
listener: Consumer<PictureInPictureModeChangedInfo>

The listener previously added with addOnPictureInPictureModeChangedListener that should be removed.

removeOnPictureInPictureUiStateChangedListener

Added in 1.13.0
final fun removeOnPictureInPictureUiStateChangedListener(
    listener: Consumer<PictureInPictureUiStateCompat>
): Unit

Remove a previously added listener. It will not receive any future callbacks.

Parameters
listener: Consumer<PictureInPictureUiStateCompat>

The listener previously added with addOnPictureInPictureUiStateChangedListener that should be removed.

removeOnTrimMemoryListener

Added in 1.5.0
final fun removeOnTrimMemoryListener(listener: Consumer<Int>): Unit

Remove a previously added listener. It will not receive any future callbacks.

Parameters
listener: Consumer<Int>

The listener previously added with .addOnTrimMemoryListener that should be removed.

removeOnUserLeaveHintListener

Added in 1.9.0
final fun removeOnUserLeaveHintListener(listener: Runnable): Unit

Remove a previously added listener. It will not receive any future callbacks.

Parameters
listener: Runnable

The listener previously added with addOnUserLeaveHintListener that should be removed.

reportFullyDrawn

open fun reportFullyDrawn(): Unit

setContentView

open fun setContentView(layoutResID: @LayoutRes Int): Unit

setContentView

open fun setContentView(view: View?): Unit

setContentView

open fun setContentView(view: View?, params: ViewGroup.LayoutParams?): Unit

setPictureInPictureParams

Added in 1.13.0
final fun setPictureInPictureParams(params: PictureInPictureParamsCompat): Unit

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
params: PictureInPictureParamsCompat

PictureInPictureParams to use for picture-in-picture mode.

startActivityForResult

Added in 1.2.0
Deprecated in 1.2.0
open fun startActivityForResult(intent: Intent, requestCode: Int): Unit

{@inheritDoc}

startActivityForResult

Added in 1.2.0
Deprecated in 1.2.0
open fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?): Unit

{@inheritDoc}

startIntentSenderForResult

Added in 1.2.0
Deprecated in 1.2.0
open fun startIntentSenderForResult(
    intent: IntentSender,
    requestCode: Int,
    fillInIntent: Intent?,
    flagsMask: Int,
    flagsValues: Int,
    extraFlags: Int
): Unit

{@inheritDoc}

startIntentSenderForResult

Added in 1.2.0
Deprecated in 1.2.0
open fun startIntentSenderForResult(
    intent: IntentSender,
    requestCode: Int,
    fillInIntent: Intent?,
    flagsMask: Int,
    flagsValues: Int,
    extraFlags: Int,
    options: Bundle?
): Unit

{@inheritDoc}

Protected functions

onActivityResult

Added in 1.2.0
Deprecated in 1.2.0
@CallSuper
protected open fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Unit

{@inheritDoc}

onCreate

protected open fun onCreate(savedInstanceState: Bundle?): Unit

{@inheritDoc}

If your ComponentActivity is annotated with ContentView, this will call setContentView for you.

onNewIntent

@CallSuper
protected open fun onNewIntent(intent: Intent): Unit

{@inheritDoc}

Dispatches this call to all listeners added via addOnNewIntentListener.

onSaveInstanceState

@CallSuper
protected open fun onSaveInstanceState(outState: Bundle): Unit

onUserLeaveHint

@CallSuper
protected open fun onUserLeaveHint(): Unit

{@inheritDoc}

Dispatches this call to all listeners added via addOnUserLeaveHintListener.

Public properties

activityResultRegistry

final val activityResultRegistryActivityResultRegistry

Get the ActivityResultRegistry associated with this activity.

defaultViewModelCreationExtras

open val defaultViewModelCreationExtrasCreationExtras

defaultViewModelProviderFactory

Added in 1.1.0
open val defaultViewModelProviderFactoryViewModelProvider.Factory

fullyDrawnReporter

open val fullyDrawnReporterFullyDrawnReporter

Retrieve the FullyDrawnReporter that should handle the independent parts of the UI that separately report that they are fully drawn.

lastCustomNonConfigurationInstance

Added in 1.0.0
Deprecated in 1.0.0
open val lastCustomNonConfigurationInstanceAny?

lifecycle

Added in 1.0.0
open val lifecycleLifecycle

{@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:

  1. Return an instance of LifecycleRegistry

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

Added in 1.12.0
open val navigationEventDispatcherNavigationEventDispatcher

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.

onBackPressedDispatcher

final val onBackPressedDispatcherOnBackPressedDispatcher

Retrieve the OnBackPressedDispatcher that will be triggered when onBackPressed is called.

Returns
OnBackPressedDispatcher

The OnBackPressedDispatcher associated with this ComponentActivity.

savedStateRegistry

Added in 1.0.0
final val savedStateRegistrySavedStateRegistry

viewModelStore

Added in 1.0.0
open val viewModelStoreViewModelStore

Extension functions

ComponentActivity.requestFullSpace

suspend fun ComponentActivity.requestFullSpace(): SpaceRequestResult

Request that the system places the application into full space mode.

In full space, this application will be the only application in the visible space, its spatial capabilities will be expanded, and its physical bounds will expand to fill the entire virtual space.

This suspend function initiates an asynchronous OS-level space change and will resume with SpaceRequestResult.Success once the application has successfully entered full space. If the device does not support XR spaces, it will resume immediately with SpaceRequestResult.Unsupported.

Note: Because Full Space Mode and Home Space Mode changes are OS-level system changes, the space switch cannot be aborted mid-flight once initiated. Cancelling this coroutine unregisters the bounds listener but does not interrupt the ongoing space change. If requestFullSpace or requestHomeSpace is called again before this request completes, the coroutine suspended on this call will be cancelled with a CancellationException.

See modes in XR.

Returns
SpaceRequestResult

SpaceRequestResult.Success if the application successfully enters full space, SpaceRequestResult.Unsupported if the device does not support XR spaces, or SpaceRequestResult.Error if a system error occurs.

ComponentActivity.requestHomeSpace

suspend fun ComponentActivity.requestHomeSpace(): SpaceRequestResult

Request that the system places the application into home space mode.

In home space, the visible space may be shared with other applications; however, applications in home space will have their spatial capabilities and physical bounds limited.

This suspend function initiates an asynchronous OS-level space change and will resume with SpaceRequestResult.Success once the application has successfully entered home space. If the device does not support XR spaces, it will resume immediately with SpaceRequestResult.Unsupported.

Note: Because Full Space Mode and Home Space Mode changes are OS-level system changes, the space switch cannot be aborted mid-flight once initiated. Cancelling this coroutine unregisters the bounds listener but does not interrupt the ongoing space change. If requestFullSpace or requestHomeSpace is called again before this request completes, the coroutine suspended on this call will be cancelled with a CancellationException.

See modes in XR.

Returns
SpaceRequestResult

SpaceRequestResult.Success if the application successfully enters home space, SpaceRequestResult.Unsupported if the device does not support XR spaces, or SpaceRequestResult.Error if a system error occurs.

ComponentActivity.viewModels

@MainThread
inline fun <VM : ViewModel> ComponentActivity.viewModels(
    noinline extrasProducer: (() -> CreationExtras)? = null,
    noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null
): Lazy<VM>

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.

ComponentActivity.registerForAuthenticationResult

fun ComponentActivity.registerForAuthenticationResult(
    resultCallback: AuthenticationResultCallback
): AuthenticationResultLauncher

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)

ComponentActivity.registerForAuthenticationResult

fun ComponentActivity.registerForAuthenticationResult(
    callbackExecutor: Executor,
    resultCallback: AuthenticationResultCallback
): AuthenticationResultLauncher

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) }
    }
}

ComponentActivity.setContent

fun ComponentActivity.setContent(
    parent: CompositionContext? = null,
    content: @Composable () -> Unit
): Unit

Composes the given composable into the given activity. The content will become the root view of the given activity.

This is roughly equivalent to calling ComponentActivity.setContentView with a ComposeView i.e.:

setContentView(
ComposeView(this).apply {
setContent {
MyComposableContent()
}
}
)
Parameters
parent: CompositionContext? = null

The parent composition reference to coordinate scheduling of composition updates

content: @Composable () -> Unit

A @Composable function declaring the UI contents

ComponentActivity.enableEdgeToEdge

fun ComponentActivity.enableEdgeToEdge(
    statusBarStyle: SystemBarStyle = SystemBarStyle.auto(Color.TRANSPARENT, Color.TRANSPARENT),
    navigationBarStyle: SystemBarStyle = SystemBarStyle.auto(DefaultLightScrim, DefaultDarkScrim)
): Unit

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
statusBarStyle: SystemBarStyle = SystemBarStyle.auto(Color.TRANSPARENT, Color.TRANSPARENT)

The SystemBarStyle for the status bar.

navigationBarStyle: SystemBarStyle = SystemBarStyle.auto(DefaultLightScrim, DefaultDarkScrim)

The SystemBarStyle for the navigation bar.