Stay organized with collections Save and categorize content based on your preferences.

ComponentActivity

public class ComponentActivity extends Activity implements LifecycleOwner, ContextAware, ViewModelStoreOwner, HasDefaultViewModelProviderFactory, SavedStateRegistryOwner, OnBackPressedDispatcherOwner, ActivityResultRegistryOwner, ActivityResultCaller, OnConfigurationChangedProvider, OnTrimMemoryProvider, OnNewIntentProvider, OnMultiWindowModeChangedProvider, OnPictureInPictureModeChangedProvider, MenuHost, FullyDrawnReporterOwner

Known direct subclasses
FragmentActivity

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

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.


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

Default constructor for ComponentActivity.

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

Public methods

void
void

Adds the given MenuProvider to this MenuHost.

void
addMenuProvider(
    @NonNull MenuProvider provider,
    @NonNull LifecycleOwner owner
)

Adds the given MenuProvider to this MenuHost.

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.

final void

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

final void

Add a new OnContextAvailableListener for receiving a callback for when this class is associated with a android.content.Context.

final void

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

final void

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

final void

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

final void

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

boolean
boolean
final @NonNull ActivityResultRegistry

Get the ActivityResultRegistry associated with this activity.

@NonNull CreationExtras

Returns the default CreationExtras that should be passed into ViewModelProvider.Factory.create when no overriding CreationExtras were passed to the ViewModelProvider constructors.

@NonNull ViewModelProvider.Factory

Returns the default ViewModelProvider.Factory that should be used when no custom Factory is provided to the ViewModelProvider constructors.

@NonNull FullyDrawnReporter

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

@Nullable Object

This method is deprecated.

Use a androidx.lifecycle.ViewModel to store non config state.

@NonNull Lifecycle

Overriding this method is no longer supported and this method will be made final in a future version of ComponentActivity.

final @NonNull OnBackPressedDispatcher

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

final @NonNull SavedStateRegistry

The SavedStateRegistry owned by this SavedStateRegistryOwner

@NonNull ViewModelStore

Returns the ViewModelStore associated with this activity

void

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

void

Called when the activity has detected the user's press of the back key.

void

Dispatches this call to all listeners added via addOnConfigurationChangedListener.

boolean
onCreatePanelMenu(int featureId, @NonNull Menu menu)
boolean
onMenuItemSelected(int featureId, @NonNull MenuItem item)
void
@CallSuper
onMultiWindowModeChanged(boolean isInMultiWindowMode)

Dispatches this call to all listeners added via addOnMultiWindowModeChangedListener.

void
@RequiresApi(api = Build.VERSION_CODES.O)
@CallSuper
onMultiWindowModeChanged(
    boolean isInMultiWindowMode,
    @NonNull Configuration newConfig
)

Dispatches this call to all listeners added via addOnMultiWindowModeChangedListener.

void
onPanelClosed(int featureId, @NonNull Menu menu)
void
@CallSuper
onPictureInPictureModeChanged(boolean isInPictureInPictureMode)

Dispatches this call to all listeners added via addOnPictureInPictureModeChangedListener.

void
@RequiresApi(api = Build.VERSION_CODES.O)
@CallSuper
onPictureInPictureModeChanged(
    boolean isInPictureInPictureMode,
    @NonNull Configuration newConfig
)

Dispatches this call to all listeners added via addOnPictureInPictureModeChangedListener.

boolean
onPreparePanel(int featureId, @Nullable View view, @NonNull Menu menu)
void
@CallSuper
onRequestPermissionsResult(
    int requestCode,
    @NonNull String[] permissions,
    @NonNull int[] grantResults
)

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your activity.

@Nullable Object

This method is deprecated.

Use a androidx.lifecycle.ViewModel to store non config state.

final @Nullable Object

Retain all appropriate non-config state.

void

Dispatches this call to all listeners added via addOnTrimMemoryListener.

@Nullable Context

Get the Context if it is currently available.

final @NonNull ActivityResultLauncher<I>
<I, O> registerForActivityResult(
    @NonNull ActivityResultContract<I, O> contract,
    @NonNull ActivityResultCallback<O> callback
)

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

final @NonNull ActivityResultLauncher<I>
<I, O> registerForActivityResult(
    @NonNull ActivityResultContract<I, O> contract,
    @NonNull ActivityResultRegistry registry,
    @NonNull ActivityResultCallback<O> callback
)

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

void

Removes the given MenuProvider from this MenuHost.

final void

Remove a previously added listener.

final void

Remove a OnContextAvailableListener previously added via addOnContextAvailableListener.

final void

Remove a previously added listener.

final void

Remove a previously added listener.

final void

Remove a previously added listener.

final void

Remove a previously added listener.

void
void
setContentView(@LayoutRes int layoutResID)
void
void
void
startActivityForResult(@NonNull Intent intent, int requestCode)

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your activity.

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

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your activity.

void
startIntentSenderForResult(
    @NonNull IntentSender intent,
    int requestCode,
    @Nullable Intent fillInIntent,
    int flagsMask,
    int flagsValues,
    int extraFlags
)

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your activity.

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

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your activity.

Protected methods

void
@CallSuper
onActivityResult(int requestCode, int resultCode, @Nullable Intent data)

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your activity.

void
onCreate(@Nullable Bundle savedInstanceState)

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

void

Dispatches this call to all listeners added via addOnNewIntentListener.

void
final boolean

Checks if the internal state should be dump, as some special args are handled by Activity itself.

Extension functions

final @NonNull Lazy<@NonNull VM>
@MainThread
<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.

Inherited Constants

From android.app.Activity
static final int
static final int
static final int
static final int
static final int
static final int[]
static final int
static final int
static final int
static final int
static final int
static final int
static final int
From android.content.ComponentCallbacks2
static final int
static final int
static final int
static final int
static final int
static final int
static final int
From android.content.Context
static final String
ACCESSIBILITY_SERVICE = "accessibility"
static final String
ACCOUNT_SERVICE = "account"
static final String
ACTIVITY_SERVICE = "activity"
static final String
ALARM_SERVICE = "alarm"
static final String
APPWIDGET_SERVICE = "appwidget"
static final String
APP_OPS_SERVICE = "appops"
static final String
APP_SEARCH_SERVICE = "app_search"
static final String
AUDIO_SERVICE = "audio"
static final String
BATTERY_SERVICE = "batterymanager"
static final int
static final int
static final int
static final int
static final int
static final int
static final int
BIND_EXTERNAL_SERVICE = -2147483648
static final long
BIND_EXTERNAL_SERVICE_LONG = 4611686018427387904
static final int
static final int
static final int
static final int
static final int
static final int
static final String
BIOMETRIC_SERVICE = "biometric"
static final String
BLOB_STORE_SERVICE = "blob_store"
static final String
BLUETOOTH_SERVICE = "bluetooth"
static final String
BUGREPORT_SERVICE = "bugreport"
static final String
CAMERA_SERVICE = "camera"
static final String
CAPTIONING_SERVICE = "captioning"
static final String
CARRIER_CONFIG_SERVICE = "carrier_config"
static final String
CLIPBOARD_SERVICE = "clipboard"
static final String
COMPANION_DEVICE_SERVICE = "companiondevice"
static final String
CONNECTIVITY_DIAGNOSTICS_SERVICE = "connectivity_diagnostics"
static final String
CONNECTIVITY_SERVICE = "connectivity"
static final String
CONSUMER_IR_SERVICE = "consumer_ir"
static final int
static final int
static final int
static final String
CREDENTIAL_SERVICE = "credential"
static final String
CROSS_PROFILE_APPS_SERVICE = "crossprofileapps"
static final int
static final int
static final String
DEVICE_LOCK_SERVICE = "device_lock"
static final String
DEVICE_POLICY_SERVICE = "device_policy"
static final String
DISPLAY_HASH_SERVICE = "display_hash"
static final String
DISPLAY_SERVICE = "display"
static final String
DOMAIN_VERIFICATION_SERVICE = "domain_verification"
static final String
DOWNLOAD_SERVICE = "download"
static final String
DROPBOX_SERVICE = "dropbox"
static final String
EUICC_SERVICE = "euicc"
static final String
FILE_INTEGRITY_SERVICE = "file_integrity"
static final String
FINGERPRINT_SERVICE = "fingerprint"
static final String
GAME_SERVICE = "game"
static final String
GRAMMATICAL_INFLECTION_SERVICE = "grammatical_inflection"
static final String
HARDWARE_PROPERTIES_SERVICE = "hardware_properties"
static final String
HEALTHCONNECT_SERVICE = "healthconnect"
static final String
INPUT_METHOD_SERVICE = "input_method"
static final String
INPUT_SERVICE = "input"
static final String
IPSEC_SERVICE = "ipsec"
static final String
JOB_SCHEDULER_SERVICE = "jobscheduler"
static final String
KEYGUARD_SERVICE = "keyguard"
static final String
LAUNCHER_APPS_SERVICE = "launcherapps"
static final String
LAYOUT_INFLATER_SERVICE = "layout_inflater"
static final String
LOCALE_SERVICE = "locale"
static final String
LOCATION_SERVICE = "location"
static final String
MEDIA_COMMUNICATION_SERVICE = "media_communication"
static final String
MEDIA_METRICS_SERVICE = "media_metrics"
static final String
MEDIA_PROJECTION_SERVICE = "media_projection"
static final String
MEDIA_ROUTER_SERVICE = "media_router"
static final String
MEDIA_SESSION_SERVICE = "media_session"
static final String
MIDI_SERVICE = "midi"
static final int
MODE_APPEND = 32768
static final int
static final int

This field is deprecated.

static final int
static final int
static final int

This field is deprecated.

static final int

This field is deprecated.

static final String
static final String
NFC_SERVICE = "nfc"
static final String
NOTIFICATION_SERVICE = "notification"
static final String
NSD_SERVICE = "servicediscovery"
static final String
OVERLAY_SERVICE = "overlay"
static final String
PEOPLE_SERVICE = "people"
static final String
PERFORMANCE_HINT_SERVICE = "performance_hint"
static final String
POWER_SERVICE = "power"
static final String
PRINT_SERVICE = "print"
static final int
static final int
static final int
static final String
RESTRICTIONS_SERVICE = "restrictions"
static final String
ROLE_SERVICE = "role"
static final String
SEARCH_SERVICE = "search"
static final String
SENSOR_SERVICE = "sensor"
static final String
SHORTCUT_SERVICE = "shortcut"
static final String
STATUS_BAR_SERVICE = "statusbar"
static final String
STORAGE_SERVICE = "storage"
static final String
STORAGE_STATS_SERVICE = "storagestats"
static final String
SYSTEM_HEALTH_SERVICE = "systemhealth"
static final String
TELECOM_SERVICE = "telecom"
static final String
TELEPHONY_IMS_SERVICE = "telephony_ims"
static final String
static final String
TELEPHONY_SUBSCRIPTION_SERVICE = "telephony_subscription_service"
static final String
TEXT_CLASSIFICATION_SERVICE = "textclassification"
static final String
static final String
TV_INPUT_SERVICE = "tv_input"
static final String
TV_INTERACTIVE_APP_SERVICE = "tv_interactive_app"
static final String
UI_MODE_SERVICE = "uimode"
static final String
USAGE_STATS_SERVICE = "usagestats"
static final String
USB_SERVICE = "usb"
static final String
USER_SERVICE = "user"
static final String
VIBRATOR_MANAGER_SERVICE = "vibrator_manager"
static final String
VIBRATOR_SERVICE = "vibrator"

This field is deprecated.

static final String
VIRTUAL_DEVICE_SERVICE = "virtualdevice"
static final String
VPN_MANAGEMENT_SERVICE = "vpn_management"
static final String
WALLPAPER_SERVICE = "wallpaper"
static final String
WIFI_AWARE_SERVICE = "wifiaware"
static final String
WIFI_P2P_SERVICE = "wifip2p"
static final String
static final String
WIFI_SERVICE = "wifi"
static final String
WINDOW_SERVICE = "window"

Inherited methods

From android.app.Activity
void
void
void
void
PendingIntent
createPendingResult(int requestCode, Intent data, int flags)
final void
dismissDialog(int id)

This method is deprecated.

final void
boolean
boolean
boolean
boolean
boolean
boolean
void
dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args)
void

This method is deprecated.

boolean
T
<T extends View> findViewById(int id)
void
void
finishActivity(int requestCode)
void
finishActivityFromChild(Activity child, int requestCode)

This method is deprecated.

void
void
void
void

This method is deprecated.

ActionBar
final Application
ComponentName
String
int
ComponentName
Scene
TransitionManager
View
FragmentManager

This method is deprecated.

Intent
Object
String
int
LayoutInflater
LoaderManager

This method is deprecated.

String
int
final MediaController
MenuInflater
OnBackInvokedDispatcher
final Activity
Intent
SharedPreferences
getPreferences(int mode)
Uri
int
final SearchEvent
final SplashScreen
Object
int
final CharSequence
final int
VoiceInteractor
final int
Window
WindowManager
boolean
void
boolean
boolean
final boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
final Cursor
managedQuery(
    Uri uri,
    String[] projection,
    String selection,
    String[] selectionArgs,
    String sortOrder
)

This method is deprecated.

boolean
moveTaskToBack(boolean nonRoot)
boolean
navigateUpTo(Intent upIntent)
boolean

This method is deprecated.

void
void
void
onActivityReenter(int resultCode, Intent data)
void
onApplyThemeResource(Resources.Theme theme, int resid, boolean first)
void

This method is deprecated.

void
void
onChildTitleChanged(Activity childActivity, CharSequence title)
void
boolean
void
void
onCreate(Bundle savedInstanceState)
void
onCreateContextMenu(
    ContextMenu menu,
    View v,
    ContextMenu.ContextMenuInfo menuInfo
)
CharSequence
Dialog

This method is deprecated.

void
boolean
View
onCreatePanelView(int featureId)
boolean
onCreateThumbnail(Bitmap outBitmap, Canvas canvas)

This method is deprecated.

View
onCreateView(String name, Context context, AttributeSet attrs)
void
void
void
boolean
void
onGetDirectActions(
    CancellationSignal cancellationSignal,
    Consumer<List<DirectAction>> callback
)
boolean
onKeyDown(int keyCode, KeyEvent event)
boolean
onKeyLongPress(int keyCode, KeyEvent event)
boolean
onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)
boolean
onKeyShortcut(int keyCode, KeyEvent event)
boolean
onKeyUp(int keyCode, KeyEvent event)
void
void
void
boolean
onMenuOpened(int featureId, Menu menu)
boolean
boolean

This method is deprecated.

boolean
void
void
void
onPerformDirectAction(
    String actionId,
    Bundle arguments,
    CancellationSignal cancellationSignal,
    Consumer<Bundle> resultListener
)
boolean
void
void
onPostCreate(Bundle savedInstanceState)
void
void
onPrepareDialog(int id, Dialog dialog)

This method is deprecated.

void
boolean
void
void
void
onProvideKeyboardShortcuts(
    List<KeyboardShortcutGroup> data,
    Menu menu,
    int deviceId
)
Uri
void
void
onRestoreInstanceState(Bundle savedInstanceState)
void
void
boolean
void
void

This method is deprecated.

void
void
onTitleChanged(CharSequence title, int color)
void
onTopResumedActivityChanged(boolean isTopResumedActivity)
boolean
boolean
void
void
void

This method is deprecated.

void
void
onWindowFocusChanged(boolean hasFocus)
ActionMode
void
void
void
overrideActivityTransition(
    int overrideType,
    int enterAnim,
    int exitAnim
)
void
overridePendingTransition(int enterAnim, int exitAnim)

This method is deprecated.

void
void
void
void
void
void
boolean
final void
removeDialog(int id)

This method is deprecated.

DragAndDropPermissions
void
requestFullscreenMode(
    int request,
    OutcomeReceiver<VoidThrowable> approvalCallback
)
final void
requestPermissions(String[] permissions, int requestCode)
final void
boolean
requestVisibleBehind(boolean visible)

This method is deprecated.

final boolean
requestWindowFeature(int featureId)
final T
<T extends View> requireViewById(int id)
final void
void
void
void
final void
void
void
final void
setFeatureDrawable(int featureId, Drawable drawable)
final void
setFeatureDrawableAlpha(int featureId, int alpha)
final void
setFeatureDrawableResource(int featureId, int resId)
final void
setFeatureDrawableUri(int featureId, Uri uri)
void
setFinishOnTouchOutside(boolean finish)
void
setImmersive(boolean i)
void
setInheritShowWhenLocked(boolean inheritShowWhenLocked)
void
setIntent(Intent newIntent)
void
setLocusContext(LocusId locusId, Bundle bundle)
final void
void
final void
setProgress(int progress)

This method is deprecated.

final void
setProgressBarIndeterminate(boolean indeterminate)

This method is deprecated.

final void

This method is deprecated.

final void
setProgressBarVisibility(boolean visible)

This method is deprecated.

void
setRecentsScreenshotEnabled(boolean enabled)
void
setRequestedOrientation(int requestedOrientation)
final void
setResult(int resultCode)
final void
setSecondaryProgress(int secondaryProgress)

This method is deprecated.

void
setShouldDockBigOverlays(boolean shouldDockBigOverlays)
void
setShowWhenLocked(boolean showWhenLocked)
void
void
setTheme(int resid)
void
void
setTitleColor(int textColor)

This method is deprecated.

boolean
setTranslucent(boolean translucent)
void
setTurnScreenOn(boolean turnScreenOn)
void
setVisible(boolean visible)
final void
setVolumeControlStream(int streamType)
void
setVrModeEnabled(boolean enabled, ComponentName requestedComponent)
boolean
boolean
boolean
boolean
final void
showDialog(int id)

This method is deprecated.

final boolean
showDialog(int id, Bundle args)

This method is deprecated.

void
ActionMode
void
startActivities(Intent[] intents)
void
void
startActivityFromChild(Activity child, Intent intent, int requestCode)

This method is deprecated.

void
startActivityFromFragment(
    Fragment fragment,
    Intent intent,
    int requestCode
)

This method is deprecated.

boolean
startActivityIfNeeded(Intent intent, int requestCode)
void
startIntentSender(
    IntentSender intent,
    Intent fillInIntent,
    int flagsMask,
    int flagsValues,
    int extraFlags
)
void
startIntentSenderFromChild(
    Activity child,
    IntentSender intent,
    int requestCode,
    Intent fillInIntent,
    int flagsMask,
    int flagsValues,
    int extraFlags
)

This method is deprecated.

void
void
void

This method is deprecated.

boolean
void
void
startSearch(
    String initialQuery,
    boolean selectInitialQuery,
    Bundle appSearchData,
    boolean globalSearch
)
void
void
void

This method is deprecated.

void
takeKeyEvents(boolean get)
void
triggerSearch(String query, Bundle appSearchData)
void
void
void
void
From android.content.Context
final int
getColor(int id)
final ColorStateList
final Drawable
getDrawable(int id)
final String
getString(int resId)
final T
<T> getSystemService(Class<T> serviceClass)
final CharSequence
getText(int resId)
final TypedArray
void
void
sendBroadcastWithMultiplePermissions(
    Intent intent,
    String[] receiverPermissions
)
From android.view.ContextThemeWrapper
From android.content.ContextWrapper
boolean
bindIsolatedService(
    Intent service,
    int flags,
    String instanceName,
    Executor executor,
    ServiceConnection conn
)
boolean
bindService(Intent service, ServiceConnection conn, int flags)
boolean
bindServiceAsUser(
    Intent service,
    ServiceConnection conn,
    int flags,
    UserHandle user
)
int
int
checkCallingOrSelfUriPermission(Uri uri, int modeFlags)
int[]
checkCallingOrSelfUriPermissions(List<Uri> uris, int modeFlags)
int
int
checkCallingUriPermission(Uri uri, int modeFlags)
int[]
checkCallingUriPermissions(List<Uri> uris, int modeFlags)
int
checkPermission(String permission, int pid, int uid)
int
int
checkUriPermission(Uri uri, int pid, int uid, int modeFlags)
int[]
checkUriPermissions(List<Uri> uris, int pid, int uid, int modeFlags)
void

This method is deprecated.

Context
Context
Context
Context
Context
createDeviceContext(int deviceId)
Context
Context
Context
createPackageContext(String packageName, int flags)
Context
createWindowContext(int type, Bundle options)
String[]
boolean
boolean
boolean
void
void
enforceCallingOrSelfUriPermission(
    Uri uri,
    int modeFlags,
    String message
)
void
enforceCallingPermission(String permission, String message)
void
enforceCallingUriPermission(Uri uri, int modeFlags, String message)
void
enforcePermission(String permission, int pid, int uid, String message)
void
enforceUriPermission(
    Uri uri,
    int pid,
    int uid,
    int modeFlags,
    String message
)
String[]
Context
ApplicationInfo
AttributionSource
String
Context
File
ClassLoader
File
ContentResolver
File
File
int
File
getDir(String name, int mode)
Display
File
File[]
File
File[]
File[]

This method is deprecated.

File
File
Executor
Looper
File
File
File[]
String
String
PackageManager
String
String
ContextParams
SharedPreferences
getSharedPreferences(String name, int mode)
String
Drawable

This method is deprecated.

int

This method is deprecated.

int

This method is deprecated.

void
grantUriPermission(String toPackage, Uri uri, int modeFlags)
boolean
boolean
boolean
boolean
moveDatabaseFrom(Context sourceContext, String name)
boolean
moveSharedPreferencesFrom(Context sourceContext, String name)
FileInputStream
FileOutputStream
openFileOutput(String name, int mode)
SQLiteDatabase
openOrCreateDatabase(
    String name,
    int mode,
    SQLiteDatabase.CursorFactory factory
)
Drawable

This method is deprecated.

void
Intent
void

This method is deprecated.

void

This method is deprecated.

void
void
revokeUriPermission(Uri uri, int modeFlags)
void
void
void
sendOrderedBroadcast(Intent intent, String receiverPermission)
void
sendOrderedBroadcastAsUser(
    Intent intent,
    UserHandle user,
    String receiverPermission,
    BroadcastReceiver resultReceiver,
    Handler scheduler,
    int initialCode,
    String initialData,
    Bundle initialExtras
)
void

This method is deprecated.

void

This method is deprecated.

void
sendStickyOrderedBroadcast(
    Intent intent,
    BroadcastReceiver resultReceiver,
    Handler scheduler,
    int initialCode,
    String initialData,
    Bundle initialExtras
)

This method is deprecated.

void
sendStickyOrderedBroadcastAsUser(
    Intent intent,
    UserHandle user,
    BroadcastReceiver resultReceiver,
    Handler scheduler,
    int initialCode,
    String initialData,
    Bundle initialExtras
)

This method is deprecated.

void

This method is deprecated.

ComponentName
boolean
startInstrumentation(
    ComponentName className,
    String profileFile,
    Bundle arguments
)
ComponentName
boolean
void
void
void
void
updateServiceGroup(ServiceConnection conn, int group, int importance)
From android.view.Window.Callback
void
onPointerCaptureChanged(boolean hasCapture)

Public constructors

ComponentActivity

public ComponentActivity()

Default constructor for ComponentActivity. All Activities must have a default constructor for API 27 and lower devices or when using the default android.app.AppComponentFactory.

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

addContentView

public void addContentView(View view, ViewGroup.LayoutParams params)

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

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<Configuration> listener
)

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

Parameters
@NonNull Consumer<Configuration> listener

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

addOnContextAvailableListener

public final void addOnContextAvailableListener(
    @NonNull OnContextAvailableListener listener
)

Add a new OnContextAvailableListener for receiving a callback for when this class is associated with a android.content.Context.

Listeners are triggered in the order they are added when added before the Context is available. Listeners added after the context has been made available will have the Context synchronously delivered to them as part of this call.

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 onCreate with the exception of restoring the state of the SavedStateRegistry for use in your listener.

addOnMultiWindowModeChangedListener

public final void addOnMultiWindowModeChangedListener(
    @NonNull Consumer<MultiWindowModeChangedInfo> listener
)

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

Parameters
@NonNull Consumer<MultiWindowModeChangedInfo> listener

The listener that should be called whenever onMultiWindowModeChanged was called.

addOnNewIntentListener

public final void addOnNewIntentListener(@NonNull Consumer<Intent> listener)

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

Parameters
@NonNull Consumer<Intent> listener

The listener that should be called whenever onNewIntent was called.

addOnPictureInPictureModeChangedListener

public final void addOnPictureInPictureModeChangedListener(
    @NonNull Consumer<PictureInPictureModeChangedInfo> listener
)

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

Parameters
@NonNull Consumer<PictureInPictureModeChangedInfo> listener

The listener that should be called whenever onPictureInPictureModeChanged was called.

addOnTrimMemoryListener

public final void addOnTrimMemoryListener(@NonNull Consumer<Integer> listener)

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

Parameters
@NonNull Consumer<Integer> listener

The listener that should be called whenever onTrimMemory was called.

dispatchKeyEvent

public boolean dispatchKeyEvent(KeyEvent event)

dispatchKeyShortcutEvent

public boolean dispatchKeyShortcutEvent(KeyEvent event)

getActivityResultRegistry

public final @NonNull ActivityResultRegistry getActivityResultRegistry()

Get the ActivityResultRegistry associated with this activity.

getDefaultViewModelCreationExtras

@CallSuper
public @NonNull CreationExtras getDefaultViewModelCreationExtras()

Returns the default CreationExtras that should be passed into ViewModelProvider.Factory.create when no overriding CreationExtras were passed to the ViewModelProvider constructors.

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

Returns the default ViewModelProvider.Factory that should be used when no custom Factory is provided to the ViewModelProvider constructors.

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.

getLastCustomNonConfigurationInstance

public @Nullable Object getLastCustomNonConfigurationInstance()

Return the value previously returned from onRetainCustomNonConfigurationInstance.

getLifecycle

public @NonNull Lifecycle getLifecycle()

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.

getOnBackPressedDispatcher

public final @NonNull OnBackPressedDispatcher getOnBackPressedDispatcher()

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

Returns
@NonNull OnBackPressedDispatcher

The OnBackPressedDispatcher associated with this ComponentActivity.

getSavedStateRegistry

public final @NonNull SavedStateRegistry getSavedStateRegistry()

The SavedStateRegistry owned by this SavedStateRegistryOwner

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

a ViewModelStore

Throws
java.lang.IllegalStateException java.lang.IllegalStateException

if called before the Activity is attached to the Application instance i.e., before onCreate()

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
public void onBackPressed()

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 onBackPressed is invoked.

onConfigurationChanged

@CallSuper
public void onConfigurationChanged(@NonNull Configuration newConfig)

Dispatches this call to all listeners added via addOnConfigurationChangedListener.

onCreatePanelMenu

public boolean onCreatePanelMenu(int featureId, @NonNull Menu menu)

onMenuItemSelected

public boolean onMenuItemSelected(int featureId, @NonNull MenuItem item)

onMultiWindowModeChanged

@CallSuper
public void onMultiWindowModeChanged(boolean isInMultiWindowMode)

Dispatches this call to all listeners added via addOnMultiWindowModeChangedListener.

onMultiWindowModeChanged

@RequiresApi(api = Build.VERSION_CODES.O)
@CallSuper
public void onMultiWindowModeChanged(
    boolean isInMultiWindowMode,
    @NonNull Configuration newConfig
)

Dispatches this call to all listeners added via addOnMultiWindowModeChangedListener.

onPanelClosed

public void onPanelClosed(int featureId, @NonNull Menu menu)

onPictureInPictureModeChanged

@CallSuper
public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode)

Dispatches this call to all listeners added via addOnPictureInPictureModeChangedListener.

onPictureInPictureModeChanged

@RequiresApi(api = Build.VERSION_CODES.O)
@CallSuper
public void onPictureInPictureModeChanged(
    boolean isInPictureInPictureMode,
    @NonNull Configuration newConfig
)

Dispatches this call to all listeners added via addOnPictureInPictureModeChangedListener.

onPreparePanel

public boolean onPreparePanel(int featureId, @Nullable View view, @NonNull Menu menu)

onRequestPermissionsResult

@CallSuper
public void onRequestPermissionsResult(
    int requestCode,
    @NonNull String[] permissions,
    @NonNull int[] grantResults
)

onRetainCustomNonConfigurationInstance

public @Nullable Object onRetainCustomNonConfigurationInstance()

Use this instead of onRetainNonConfigurationInstance. Retrieve later with getLastCustomNonConfigurationInstance.

onRetainNonConfigurationInstance

public final @Nullable 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)

Dispatches this call to all listeners added via addOnTrimMemoryListener.

peekAvailableContext

public @Nullable 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
@Nullable Context

the Context if it is currently available.

registerForActivityResult

public final @NonNull ActivityResultLauncher<I> <I, O> registerForActivityResult(
    @NonNull ActivityResultContract<I, O> contract,
    @NonNull ActivityResultCallback<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>

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

<O>

the type of output returned as an activity result

@NonNull ActivityResultContract<I, O> contract

the contract, specifying conversions to/from Intents

@NonNull ActivityResultCallback<O> callback

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

Returns
@NonNull ActivityResultLauncher<I>

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

registerForActivityResult

public final @NonNull ActivityResultLauncher<I> <I, O> registerForActivityResult(
    @NonNull ActivityResultContract<I, O> contract,
    @NonNull ActivityResultRegistry registry,
    @NonNull ActivityResultCallback<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>

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

<O>

the type of output returned as an activity result

@NonNull ActivityResultContract<I, O> contract

the contract, specifying conversions to/from Intents

@NonNull ActivityResultRegistry registry

the registry where to hold the record.

@NonNull ActivityResultCallback<O> callback

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

Returns
@NonNull ActivityResultLauncher<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<Configuration> listener
)

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

Parameters
@NonNull Consumer<Configuration> listener

The listener previously added with addOnConfigurationChangedListener that should be removed.

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.

removeOnMultiWindowModeChangedListener

public final void removeOnMultiWindowModeChangedListener(
    @NonNull Consumer<MultiWindowModeChangedInfo> listener
)

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

Parameters
@NonNull Consumer<MultiWindowModeChangedInfo> listener

The listener previously added with addOnMultiWindowModeChangedListener that should be removed.

removeOnNewIntentListener

public final void removeOnNewIntentListener(@NonNull Consumer<Intent> listener)

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

Parameters
@NonNull Consumer<Intent> listener

The listener previously added with addOnNewIntentListener that should be removed.

removeOnPictureInPictureModeChangedListener

public final void removeOnPictureInPictureModeChangedListener(
    @NonNull Consumer<PictureInPictureModeChangedInfo> listener
)

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

Parameters
@NonNull Consumer<PictureInPictureModeChangedInfo> listener

The listener previously added with addOnPictureInPictureModeChangedListener that should be removed.

removeOnTrimMemoryListener

public final void removeOnTrimMemoryListener(@NonNull Consumer<Integer> listener)

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

Parameters
@NonNull Consumer<Integer> listener

The listener previously added with addOnTrimMemoryListener that should be removed.

reportFullyDrawn

public void reportFullyDrawn()

setContentView

public void setContentView(@LayoutRes int layoutResID)

setContentView

public void setContentView(View view)

setContentView

public void setContentView(View view, ViewGroup.LayoutParams params)

startActivityForResult

public void startActivityForResult(@NonNull Intent intent, int requestCode)

startActivityForResult

public void startActivityForResult(
    @NonNull Intent intent,
    int requestCode,
    @Nullable Bundle options
)

startIntentSenderForResult

public void startIntentSenderForResult(
    @NonNull IntentSender intent,
    int requestCode,
    @Nullable Intent fillInIntent,
    int flagsMask,
    int flagsValues,
    int extraFlags
)
Throws
android.content.IntentSender.SendIntentException android.content.IntentSender.SendIntentException

startIntentSenderForResult

public void startIntentSenderForResult(
    @NonNull IntentSender intent,
    int requestCode,
    @Nullable Intent fillInIntent,
    int flagsMask,
    int flagsValues,
    int extraFlags,
    @Nullable Bundle options
)
Throws
android.content.IntentSender.SendIntentException android.content.IntentSender.SendIntentException

Protected methods

onActivityResult

@CallSuper
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)

onCreate

protected void onCreate(@Nullable Bundle savedInstanceState)

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

onNewIntent

@CallSuper
protected void onNewIntent(Intent intent)

Dispatches this call to all listeners added via addOnNewIntentListener.

onSaveInstanceState

@CallSuper
protected void onSaveInstanceState(@NonNull Bundle outState)

shouldDumpInternalState

protected final boolean shouldDumpInternalState(@Nullable String[] args)

Checks if the internal state should be dump, as some special args are handled by Activity itself.

Subclasses implementing dump should typically start with:

@Override
public void dump(@NonNull String prefix, @Nullable FileDescriptor fd,
       @NonNull PrintWriter writer, @Nullable String[] args) {
   super.dump(prefix, fd, writer, args);

   if (!shouldDumpInternalState(args)) {
       return;
   }
   // dump internal starte
}

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.