Added in API level 1
Deprecated in API level 30

LauncherActivity


abstract class LauncherActivity : ListActivity

Displays a list of all activities which can be performed for a given intent. Launches when clicked.

Summary

Nested classes
open

Utility class to resize icons to match default icon size.

open

An item in the list

Inherited constants
String ACCESSIBILITY_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.view.accessibility.AccessibilityManager for giving the user feedback for UI events through the registered event listeners.

String ACCOUNT_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.accounts.AccountManager for receiving intents at a time of your choosing.

String ACTIVITY_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.app.ActivityManager for interacting with the global system state.

String ADVANCED_PROTECTION_SERVICE

Use with getSystemService(java.lang.String) to retrieve an android.security.advancedprotection.AdvancedProtectionManager

String ALARM_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.app.AlarmManager for receiving intents at a time of your choosing.

String APPWIDGET_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.appwidget.AppWidgetManager for accessing AppWidgets.

String APP_FUNCTION_SERVICE

Use with getSystemService(java.lang.String) to retrieve an AppFunctionManager for executing app functions.

String APP_OPS_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.app.AppOpsManager for tracking application operations on the device.

String APP_SEARCH_SERVICE

Use with getSystemService(java.lang.String) to retrieve an android.app.appsearch.AppSearchManager for indexing and querying app data managed by the system.

String AUDIO_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.media.AudioManager for handling management of volume, ringer modes and audio routing.

String BATTERY_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.os.BatteryManager for managing battery state.

Int BIND_ABOVE_CLIENT

Flag for #bindService: indicates that the client application binding to this service considers the service to be more important than the app itself. When set, the platform will try to have the out of memory killer kill the app before it kills the service it is bound to, though this is not guaranteed to be the case.

Int BIND_ADJUST_WITH_ACTIVITY

Flag for #bindService: If binding from an activity, allow the target service's process importance to be raised based on whether the activity is visible to the user, regardless whether another flag is used to reduce the amount that the client process's overall importance is used to impact it.

Int BIND_ALLOW_ACTIVITY_STARTS

Flag for #bindService: If binding from an app that is visible, the bound service is allowed to start an activity from background. This was the default behavior before SDK version android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE. Since then, the default behavior changed to disallow the bound service to start a background activity even if the app bound to it is in foreground, unless this flag is specified when binding.

Int BIND_ALLOW_OOM_MANAGEMENT

Flag for #bindService: allow the process hosting the bound service to go through its normal memory management. It will be treated more like a running service, allowing the system to (temporarily) expunge the process if low on memory or for some other whim it may have, and being more aggressive about making it a candidate to be killed (and restarted) if running for a long time.

Int BIND_AUTO_CREATE

Flag for #bindService: automatically create the service as long as the binding exists. Note that while this will create the service, its android.app.Service#onStartCommand method will still only be called due to an explicit call to startService. Even without that, though, this still provides you with access to the service object while the service is created.

Note that prior to android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH, not supplying this flag would also impact how important the system consider's the target service's process to be. When set, the only way for it to be raised was by binding from a service in which case it will only be important when that activity is in the foreground. Now to achieve this behavior you must explicitly supply the new flag BIND_ADJUST_WITH_ACTIVITY. For compatibility, old applications that don't specify BIND_AUTO_CREATE will automatically have the flags BIND_WAIVE_PRIORITY and BIND_ADJUST_WITH_ACTIVITY set for them in order to achieve the same result.

Int BIND_DEBUG_UNBIND

Flag for #bindService: include debugging help for mismatched calls to unbind. When this flag is set, the callstack of the following unbindService call is retained, to be printed if a later incorrect unbind call is made. Note that doing this requires retaining information about the binding that was made for the lifetime of the app, resulting in a leak -- this should only be used for debugging.

Int BIND_EXTERNAL_SERVICE

Flag for #bindService: The service being bound is an isolated, external service. This binds the service into the calling application's package, rather than the package in which the service is declared.

When using this flag, the code for the service being bound will execute under the calling application's package name and user ID. Because the service must be an isolated process, it will not have direct access to the application's data, though. The purpose of this flag is to allow applications to provide services that are attributed to the app using the service, rather than the application providing the service.

This flag is NOT compatible with BindServiceFlags. If you need to use BindServiceFlags, you must use BIND_EXTERNAL_SERVICE_LONG instead.

Long BIND_EXTERNAL_SERVICE_LONG

Works in the same way as BIND_EXTERNAL_SERVICE, but it's defined as a long value that is compatible to BindServiceFlags.

Int BIND_IMPORTANT

Flag for #bindService: this service is very important to the client, so should be brought to the foreground process level when the client is. Normally a process can only be raised to the visibility level by a client, even if that client is in the foreground.

Int BIND_INCLUDE_CAPABILITIES

Flag for #bindService: If binding from an app that has specific capabilities due to its foreground state such as an activity or foreground service, then this flag will allow the bound app to get the same capabilities, as long as it has the required permissions as well. If binding from a top app and its target SDK version is at or above android.os.Build.VERSION_CODES#R, the app needs to explicitly use BIND_INCLUDE_CAPABILITIES flag to pass all capabilities to the service so the other app can have while-in-use access such as location, camera, microphone from background. If binding from a top app and its target SDK version is below android.os.Build.VERSION_CODES#R, BIND_INCLUDE_CAPABILITIES is implicit.

Int BIND_NOT_FOREGROUND

Flag for #bindService: don't allow this binding to raise the target service's process to the foreground scheduling priority. It will still be raised to at least the same memory priority as the client (so that its process will not be killable in any situation where the client is not killable), but for CPU scheduling purposes it may be left in the background. This only has an impact in the situation where the binding client is a foreground process and the target service is in a background process.

Int BIND_NOT_PERCEPTIBLE

Flag for #bindService: If binding from an app that is visible or user-perceptible, lower the target service's importance to below the perceptible level. This allows the system to (temporarily) expunge the bound process from memory to make room for more important user-perceptible processes.

Int BIND_PACKAGE_ISOLATED_PROCESS

Flag for #bindIsolatedService: Bind the service into a shared isolated process, but only with other isolated services from the same package that declare the same process name.

Specifying this flag allows multiple isolated services defined in the same package to be running in a single shared isolated process. This shared isolated process must be specified since this flag will not work with the default application process.

This flag is different from BIND_SHARED_ISOLATED_PROCESS since it only allows binding services from the same package in the same shared isolated process. This also means the shared package isolated process is global, and not scoped to each potential calling app.

The shared isolated process instance is identified by the "android:process" attribute defined by the service. This flag cannot be used without this attribute set.

Int BIND_SHARED_ISOLATED_PROCESS

Flag for #bindIsolatedService: Bind the service into a shared isolated process. Specifying this flag allows multiple isolated services to be running in a single shared isolated process. The shared isolated process instance is identified by the instanceName parameter in bindIsolatedService(android.content.Intent,int,java.lang.String,java.util.concurrent.Executor,android.content.ServiceConnection). Subsequent calls to #bindIsolatedService with the same instanceName will cause the isolated service to be co-located in the same shared isolated process. Note that the shared isolated process is scoped to the calling app; once created, only the calling app can bind additional isolated services into the shared process. However, the services themselves can come from different APKs and therefore different vendors. Only services that set the android.R.attr#allowSharedIsolatedProcess attribute to true are allowed to be bound into a shared isolated process.

Int BIND_WAIVE_PRIORITY

Flag for #bindService: don't impact the scheduling or memory management priority of the target service's hosting process. Allows the service's process to be managed on the background LRU list just like a regular application process in the background.

String BIOMETRIC_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.hardware.biometrics.BiometricManager for handling biometric and PIN/pattern/password authentication.

String BLOB_STORE_SERVICE

Use with getSystemService(java.lang.String) to retrieve a for contributing and accessing data blobs from the blob store maintained by the system.

String BLUETOOTH_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.bluetooth.BluetoothManager for using Bluetooth.

String BUGREPORT_SERVICE

Service to capture a bugreport.

String CAMERA_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.hardware.camera2.CameraManager for interacting with camera devices.

String CAPTIONING_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.view.accessibility.CaptioningManager for obtaining captioning properties and listening for changes in captioning preferences.

String CARRIER_CONFIG_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.telephony.CarrierConfigManager for reading carrier configuration values.

String CLIPBOARD_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.content.ClipboardManager for accessing and modifying the contents of the global clipboard.

String COMPANION_DEVICE_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.companion.CompanionDeviceManager for managing companion devices

String CONNECTIVITY_DIAGNOSTICS_SERVICE

Use with getSystemService(java.lang.String) to retrieve a for performing network connectivity diagnostics as well as receiving network connectivity information from the system.

String CONNECTIVITY_SERVICE

Use with getSystemService(java.lang.String) to retrieve a for handling management of network connections.

String CONSUMER_IR_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.hardware.ConsumerIrManager for transmitting infrared signals from the device.

String CONTACT_KEYS_SERVICE

Use with getSystemService(java.lang.String) to retrieve a E2eeContactKeysManager to managing contact keys.

Int CONTEXT_IGNORE_SECURITY

Flag for use with createPackageContext: ignore any security restrictions on the Context being requested, allowing it to always be loaded. For use with CONTEXT_INCLUDE_CODE to allow code to be loaded into a process even when it isn't safe to do so. Use with extreme care!

Int CONTEXT_INCLUDE_CODE

Flag for use with createPackageContext: include the application code with the context. This means loading code into the caller's process, so that getClassLoader() can be used to instantiate the application's classes. Setting this flags imposes security restrictions on what application context you can access; if the requested application can not be safely loaded into your process, java.lang.SecurityException will be thrown. If this flag is not set, there will be no restrictions on the packages that can be loaded, but getClassLoader will always return the default system class loader.

Int CONTEXT_RESTRICTED

Flag for use with createPackageContext: a restricted context may disable specific features. For instance, a View associated with a restricted context would ignore particular XML attributes.

String CREDENTIAL_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.credentials.CredentialManager to authenticate a user to your app.

String CROSS_PROFILE_APPS_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.content.pm.CrossProfileApps for cross profile operations.

Int DEVICE_ID_DEFAULT

The default device ID, which is the ID of the primary (non-virtual) device.

Int DEVICE_ID_INVALID

Invalid device ID.

String DEVICE_LOCK_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.devicelock.DeviceLockManager.

String DEVICE_POLICY_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.app.admin.DevicePolicyManager for working with global device policy management.

String DISPLAY_HASH_SERVICE

Use with getSystemService(java.lang.String) to access android.view.displayhash.DisplayHashManager to handle display hashes.

String DISPLAY_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.hardware.display.DisplayManager for interacting with display devices.

String DOMAIN_VERIFICATION_SERVICE

Use with getSystemService(java.lang.String) to access android.content.pm.verify.domain.DomainVerificationManager to retrieve approval and user state for declared web domains.

String DOWNLOAD_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.app.DownloadManager for requesting HTTP downloads.

String DROPBOX_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.os.DropBoxManager instance for recording diagnostic logs.

String EUICC_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.telephony.euicc.EuiccManager to manage the device eUICC (embedded SIM).

String FILE_INTEGRITY_SERVICE

Use with getSystemService(java.lang.String) to retrieve an android.security.FileIntegrityManager.

String FINGERPRINT_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.hardware.fingerprint.FingerprintManager for handling management of fingerprints.

String GAME_SERVICE

Use with getSystemService(java.lang.String) to retrieve a GameManager.

String GRAMMATICAL_INFLECTION_SERVICE

Use with getSystemService(java.lang.String) to retrieve a GrammaticalInflectionManager.

String HARDWARE_PROPERTIES_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.os.HardwarePropertiesManager for accessing the hardware properties service.

String HEALTHCONNECT_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.health.connect.HealthConnectManager.

String INPUT_METHOD_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.view.inputmethod.InputMethodManager for accessing input methods.

String INPUT_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.hardware.input.InputManager for interacting with input devices.

String IPSEC_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.net.IpSecManager for encrypting Sockets or Networks with IPSec.

String JOB_SCHEDULER_SERVICE

Use with getSystemService(java.lang.String) to retrieve a instance for managing occasional background tasks.

String KEYGUARD_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.app.KeyguardManager for controlling keyguard.

String KEYSTORE_SERVICE

Use with getSystemService(java.lang.String) to retrieve a for accessing Android Keystore functions.

String LAUNCHER_APPS_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.content.pm.LauncherApps for querying and monitoring launchable apps across profiles of a user.

String LAYOUT_INFLATER_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.view.LayoutInflater for inflating layout resources in this context.

String LOCALE_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.app.LocaleManager.

String LOCATION_SERVICE

Use with getSystemService(java.lang.String) to retrieve a for controlling location updates.

String MEDIA_COMMUNICATION_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.media.MediaCommunicationManager for managing android.media.MediaSession2.

String MEDIA_METRICS_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.media.metrics.MediaMetricsManager for interacting with media metrics on the device.

String MEDIA_PROJECTION_SERVICE

Use with getSystemService(java.lang.String) to retrieve a instance for managing media projection sessions.

String MEDIA_QUALITY_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.media.quality.MediaQuality for standardize picture and audio API parameters.

String MEDIA_ROUTER_SERVICE

Use with #getSystemService to retrieve a android.media.MediaRouter for controlling and managing routing of media.

String MEDIA_SESSION_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.media.session.MediaSessionManager for managing media Sessions.

String MIDI_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.media.midi.MidiManager for accessing the MIDI service.

Int MODE_APPEND

File creation mode: for use with openFileOutput, if the file already exists then write data to the end of the existing file instead of erasing it.

Int MODE_ENABLE_WRITE_AHEAD_LOGGING

Database open flag: when set, the database is opened with write-ahead logging enabled by default.

Int MODE_MULTI_PROCESS

SharedPreference loading flag: when set, the file on disk will be checked for modification even if the shared preferences instance is already loaded in this process. This behavior is sometimes desired in cases where the application has multiple processes, all writing to the same SharedPreferences file. Generally there are better forms of communication between processes, though.

This was the legacy (but undocumented) behavior in and before Gingerbread (Android 2.3) and this flag is implied when targeting such releases. For applications targeting SDK versions greater than Android 2.3, this flag must be explicitly set if desired.

Int MODE_NO_LOCALIZED_COLLATORS

Database open flag: when set, the database is opened without support for localized collators.

Int MODE_PRIVATE

File creation mode: the default mode, where the created file can only be accessed by the calling application (or all applications sharing the same user ID).

Int MODE_WORLD_READABLE

File creation mode: allow all other applications to have read access to the created file.

Starting from android.os.Build.VERSION_CODES#N, attempting to use this mode throws a SecurityException.

Int MODE_WORLD_WRITEABLE

File creation mode: allow all other applications to have write access to the created file.

Starting from android.os.Build.VERSION_CODES#N, attempting to use this mode will throw a SecurityException.

String NETWORK_STATS_SERVICE

Use with getSystemService(java.lang.String) to retrieve a for querying network usage stats.

String NFC_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.nfc.NfcManager for using NFC.

String NOTIFICATION_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.app.NotificationManager for informing the user of background events.

String NSD_SERVICE

Use with getSystemService(java.lang.String) to retrieve a for handling management of network service discovery

String OVERLAY_SERVICE

Use with getSystemService(java.lang.String) to retrieve a for managing overlay packages.

String PEOPLE_SERVICE

Use with getSystemService(java.lang.String) to access a PeopleManager to interact with your published conversations.

String PERFORMANCE_HINT_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.os.PerformanceHintManager for accessing the performance hinting service.

String PERSISTENT_DATA_BLOCK_SERVICE

Use with getSystemService(java.lang.String) to retrieve a instance for interacting with a storage device that lives across factory resets.

String POWER_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.os.PowerManager for controlling power management, including "wake locks," which let you keep the device on while you're running long tasks.

String PRINT_SERVICE

android.print.PrintManager for printing and managing printers and print tasks.

String PROFILING_SERVICE

Use with getSystemService(java.lang.String) to retrieve an android.os.ProfilingManager.

Int RECEIVER_EXPORTED

Flag for #registerReceiver: The receiver can receive broadcasts from other Apps. Has the same behavior as marking a statically registered receiver with "exported=true"

Int RECEIVER_NOT_EXPORTED

Flag for #registerReceiver: The receiver cannot receive broadcasts from other Apps. Has the same behavior as marking a statically registered receiver with "exported=false"

Int RECEIVER_VISIBLE_TO_INSTANT_APPS

Flag for #registerReceiver: The receiver can receive broadcasts from Instant Apps.

String RESTRICTIONS_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.content.RestrictionsManager for retrieving application restrictions and requesting permissions for restricted operations.

String ROLE_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.app.role.RoleManager for managing roles.

String SATELLITE_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.telephony.satellite.SatelliteManager for accessing satellite functionality.

String SEARCH_SERVICE

Use with getSystemService(java.lang.String) to retrieve a for handling searches.

Configuration.UI_MODE_TYPE_WATCH does not support android.app.SearchManager.

String SECURITY_STATE_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.os.SecurityStateManager for accessing the security state manager service.

String SENSOR_SERVICE

Use with getSystemService(java.lang.String) to retrieve a for accessing sensors.

String SHORTCUT_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.content.pm.ShortcutManager for accessing the launcher shortcut service.

String STATUS_BAR_SERVICE

Use with getSystemService(java.lang.String) to retrieve a for interacting with the status bar and quick settings.

String STORAGE_SERVICE

Use with getSystemService(java.lang.String) to retrieve a for accessing system storage functions.

String STORAGE_STATS_SERVICE

Use with getSystemService(java.lang.String) to retrieve a for accessing system storage statistics.

String SYSTEM_HEALTH_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.os.health.SystemHealthManager for accessing system health (battery, power, memory, etc) metrics.

String TELECOM_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.telecom.TelecomManager to manage telecom-related features of the device.

String TELEPHONY_IMS_SERVICE

Use with getSystemService(java.lang.String) to retrieve an android.telephony.ims.ImsManager.

String TELEPHONY_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.telephony.TelephonyManager for handling management the telephony features of the device.

String TELEPHONY_SUBSCRIPTION_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.telephony.SubscriptionManager for handling management the telephony subscriptions of the device.

String TEXT_CLASSIFICATION_SERVICE

Use with getSystemService(java.lang.String) to retrieve a TextClassificationManager for text classification services.

String TEXT_SERVICES_MANAGER_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.view.textservice.TextServicesManager for accessing text services.

String TV_AD_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.media.tv.ad.TvAdManager for interacting with TV client-side advertisement services on the device.

String TV_INPUT_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.media.tv.TvInputManager for interacting with TV inputs on the device.

String TV_INTERACTIVE_APP_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.media.tv.interactive.TvInteractiveAppManager for interacting with TV interactive applications on the device.

String UI_MODE_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.app.UiModeManager for controlling UI modes.

String USAGE_STATS_SERVICE

Use with getSystemService(java.lang.String) to retrieve a for querying device usage stats.

String USB_SERVICE

Use with getSystemService(java.lang.String) to retrieve a for access to USB devices (as a USB host) and for controlling this device's behavior as a USB device.

String USER_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.os.UserManager for managing users on devices that support multiple users.

String VIBRATOR_MANAGER_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.os.VibratorManager for accessing the device vibrators, interacting with individual ones and playing synchronized effects on multiple vibrators.

String VIBRATOR_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.os.Vibrator for interacting with the vibration hardware.

String VIRTUAL_DEVICE_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.companion.virtual.VirtualDeviceManager for managing virtual devices. On devices without PackageManager.FEATURE_COMPANION_DEVICE_SETUP system feature the getSystemService(java.lang.String) will return null.

String VPN_MANAGEMENT_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.net.VpnManager to manage profiles for the platform built-in VPN.

String WALLPAPER_SERVICE

Use with getSystemService(java.lang.String) to retrieve a com.android.server.WallpaperService for accessing wallpapers.

String WIFI_AWARE_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.net.wifi.aware.WifiAwareManager for handling management of Wi-Fi Aware.

String WIFI_P2P_SERVICE

Use with getSystemService(java.lang.String) to retrieve a for handling management of Wi-Fi peer-to-peer connections.

String WIFI_RTT_RANGING_SERVICE

Use with getSystemService(java.lang.String) to retrieve a for ranging devices with wifi.

String WIFI_SERVICE

Use with getSystemService(java.lang.String) to retrieve a for handling management of Wi-Fi access.

String WINDOW_SERVICE

Use with getSystemService(java.lang.String) to retrieve a android.view.WindowManager for accessing the system's window manager.

Int DEFAULT_KEYS_DIALER

Use with setDefaultKeyMode to launch the dialer during default key handling.

Int DEFAULT_KEYS_DISABLE

Use with setDefaultKeyMode to turn off default handling of keys.

Int DEFAULT_KEYS_SEARCH_GLOBAL

Use with setDefaultKeyMode to specify that unhandled keystrokes will start a global search (typically web search, but some platforms may define alternate methods for global search)

See android.app.SearchManager for more details.

Int DEFAULT_KEYS_SEARCH_LOCAL

Use with setDefaultKeyMode to specify that unhandled keystrokes will start an application-defined search. (If the application or activity does not actually define a search, the keys will be ignored.)

See android.app.SearchManager for more details.

Int DEFAULT_KEYS_SHORTCUT

Use with setDefaultKeyMode to execute a menu shortcut in default key handling.

That is, the user does not need to hold down the menu key to execute menu shortcuts.

Int FULLSCREEN_MODE_REQUEST_ENTER

Request type of requestFullscreenMode(int,android.os.OutcomeReceiver), to request enter fullscreen mode from multi-window mode.

Int FULLSCREEN_MODE_REQUEST_EXIT

Request type of requestFullscreenMode(int,android.os.OutcomeReceiver), to request exiting the requested fullscreen mode and restore to the previous multi-window mode.

Int OVERRIDE_TRANSITION_CLOSE

Request type of overrideActivityTransition(int,int,int) or overrideActivityTransition(int,int,int,int), to override the closing transition.

Int OVERRIDE_TRANSITION_OPEN

Request type of overrideActivityTransition(int,int,int) or overrideActivityTransition(int,int,int,int), to override the opening transition.

Int RESULT_CANCELED

Standard activity result: operation canceled.

Int RESULT_FIRST_USER

Start of user-defined activity results.

Int RESULT_OK

Standard activity result: operation succeeded.

Int TRIM_MEMORY_BACKGROUND

Level for onTrimMemory(int): the process has gone on to the LRU list. This is a good opportunity to clean up resources that can efficiently and quickly be re-built if the user returns to the app.

Int TRIM_MEMORY_COMPLETE

Level for onTrimMemory(int): the process is nearing the end of the background LRU list, and if more memory isn't found soon it will be killed.

Int TRIM_MEMORY_MODERATE

Level for onTrimMemory(int): the process is around the middle of the background LRU list; freeing memory can help the system keep other processes running later in the list for better overall performance.

Int TRIM_MEMORY_RUNNING_CRITICAL

Level for onTrimMemory(int): the process is not an expendable background process, but the device is running extremely low on memory and is about to not be able to keep any background processes running. Your running process should free up as many non-critical resources as it can to allow that memory to be used elsewhere. The next thing that will happen after this is onLowMemory() called to report that nothing at all can be kept in the background, a situation that can start to notably impact the user.

Int TRIM_MEMORY_RUNNING_LOW

Level for onTrimMemory(int): the process is not an expendable background process, but the device is running low on memory. Your running process should free up unneeded resources to allow that memory to be used elsewhere.

Int TRIM_MEMORY_RUNNING_MODERATE

Level for onTrimMemory(int): the process is not an expendable background process, but the device is running moderately low on memory. Your running process may want to release some unneeded resources for use elsewhere.

Int TRIM_MEMORY_UI_HIDDEN

Level for onTrimMemory(int): the process had been showing a user interface, and is no longer doing so. Large allocations with the UI should be released at this point to allow memory to be better managed.

Public constructors

Public methods
open MutableList<LauncherActivity.ListItem!>!

Perform the query to determine which results to show and return a list of them.

open Unit
setTitle(titleId: Int)

open Unit

Protected methods
open Intent!

Get the base intent to use when running PackageManager.queryIntentActivities(Intent, int).

open Intent!

Return the actual Intent for a specific position in our android.widget.ListView.

open LauncherActivity.ListItem!
itemForPosition(position: Int)

Return the ListItem for a specific position in our android.widget.ListView.

open Unit
onCreate(icicle: Bundle?)

open Unit
onListItemClick(l: ListView!, v: View!, position: Int, id: Long)

open MutableList<ResolveInfo!>!

Perform query on package manager for list items.

open Unit

Override to call setContentView() with your own content view to customize the list layout.

Inherited functions
Unit addContentView(view: View!, params: ViewGroup.LayoutParams!)

Add an additional content view to the activity. Added after any existing ones in the activity -- existing views are NOT removed.

Unit attachBaseContext(newBase: Context!)

Unit clearOverrideActivityTransition(overrideType: Int)

Clears the animations which are set from #overrideActivityTransition.

Unit closeContextMenu()

Programmatically closes the most recently opened context menu, if showing.

Unit closeOptionsMenu()

Progammatically closes the options menu. If the options menu is already closed, this method does nothing.

PendingIntent! createPendingResult(requestCode: Int, data: Intent, flags: Int)

Create a new PendingIntent object which you can hand to others for them to use to send result data back to your #onActivityResult callback. The created object will be either one-shot (becoming invalid after a result is sent back) or multiple (allowing any number of results to be sent through it).

Unit dismissDialog(id: Int)

Dismiss a dialog that was previously shown via showDialog(int).

Unit dismissKeyboardShortcutsHelper()

Dismiss the Keyboard Shortcuts screen.

Boolean dispatchGenericMotionEvent(ev: MotionEvent!)

Called to process generic motion events. You can override this to intercept all generic motion events before they are dispatched to the window. Be sure to call this implementation for generic motion events that should be handled normally.

Boolean dispatchKeyEvent(event: KeyEvent!)

Called to process key events. You can override this to intercept all key events before they are dispatched to the window. Be sure to call this implementation for key events that should be handled normally.

Boolean dispatchKeyShortcutEvent(event: KeyEvent!)

Called to process a key shortcut event. You can override this to intercept all key shortcut events before they are dispatched to the window. Be sure to call this implementation for key shortcut events that should be handled normally.

Boolean dispatchPopulateAccessibilityEvent(event: AccessibilityEvent!)

Boolean dispatchTouchEvent(ev: MotionEvent!)

Called to process touch screen events. You can override this to intercept all touch screen events before they are dispatched to the window. Be sure to call this implementation for touch screen events that should be handled normally.

Boolean dispatchTrackballEvent(ev: MotionEvent!)

Called to process trackball events. You can override this to intercept all trackball events before they are dispatched to the window. Be sure to call this implementation for trackball events that should be handled normally.

Unit dump(prefix: String, fd: FileDescriptor?, writer: PrintWriter, args: Array<String!>?)

Print the Activity's state into the given stream. This gets invoked if you run adb shell dumpsys activity <activity_component_name>.

This method won't be called if the app targets android.os.Build.VERSION_CODES#TIRAMISU or later if the dump request starts with one of the following arguments:

  • --autofill
  • --contentcapture
  • --translation
  • --list-dumpables
  • --dump-dumpable

Unit enterPictureInPictureMode()

Puts the activity in picture-in-picture mode if possible in the current system state. Any prior calls to setPictureInPictureParams(android.app.PictureInPictureParams) will still apply when entering picture-in-picture through this call.

Boolean enterPictureInPictureMode(params: PictureInPictureParams)

Puts the activity in picture-in-picture mode if possible in the current system state. The set parameters in {@param params} will be combined with the parameters from prior calls to setPictureInPictureParams(android.app.PictureInPictureParams). The system may disallow entering picture-in-picture in various cases, including when the activity is not visible, if the screen is locked or if the user has an activity pinned.

By default, system calculates the dimension of picture-in-picture window based on the given {@param params}. See Picture-in-picture Support on how to override this behavior.

T findViewById(id: Int)

Finds a view that was identified by the android:id XML attribute that was processed in #onCreate.

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

Unit finish()

Call this when your activity is done and should be closed. The ActivityResult is propagated back to whoever launched you via onActivityResult().

Unit finishActivity(requestCode: Int)

Force finish another activity that you had previously started with #startActivityForResult.

Unit finishActivityFromChild(child: Activity, requestCode: Int)

This is called when a child activity of this one calls its finishActivity().

Unit finishAffinity()

Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and in to its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch.

Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.

Unit finishAfterTransition()

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

Unit finishAndRemoveTask()

Call this when your activity is done and should be closed and the task should be completely removed as a part of finishing the root activity of the task.

Unit finishFromChild(child: Activity!)

This is called when a child activity of this one calls its finish method. The default implementation simply calls finish() on this activity (the parent), finishing the entire group.

ActionBar? getActionBar()

Retrieve a reference to this activity's ActionBar.

Application! getApplication()

Return the application that owns this activity.

ComponentCaller? getCaller()

Returns the ComponentCaller instance of the app that started this activity.

To keep the ComponentCaller instance for future use, call setIntent(android.content.Intent,android.app.ComponentCaller), and use this method to retrieve it.

Note that in #onNewIntent, this method will return the original ComponentCaller. You can use setIntent(android.content.Intent,android.app.ComponentCaller) to update it to the new ComponentCaller.

ComponentName? getCallingActivity()

Return the name of the activity that invoked this activity. This is who the data in #setResult will be sent to. You can use this information to validate that the recipient is allowed to receive the data.

Note: if the calling activity is not expecting a result (that is it did not use the #startActivityForResult form that includes a request code), then the calling package will be null.

String? getCallingPackage()

Return the name of the package that invoked this activity. This is who the data in #setResult will be sent to. You can use this information to validate that the recipient is allowed to receive the data.

Note: if the calling activity is not expecting a result (that is it did not use the #startActivityForResult form that includes a request code), then the calling package will be null.

Note: prior to android.os.Build.VERSION_CODES#JELLY_BEAN_MR2, the result from this method was unstable. If the process hosting the calling package was no longer running, it would return null instead of the proper package name. You can use getCallingActivity() and retrieve the package name from that instead.

Int getChangingConfigurations()

If this activity is being destroyed because it can not handle a configuration parameter being changed (and thus its onConfigurationChanged(android.content.res.Configuration) method is not being called), then you can use this method to discover the set of changes that have occurred while in the process of being destroyed. Note that there is no guarantee that these will be accurate (other changes could have happened at any time), so you should only use this as an optimization hint.

ComponentName! getComponentName()

Returns the complete component name of this activity.

Scene! getContentScene()

Retrieve the Scene representing this window's current content. Requires Window.FEATURE_CONTENT_TRANSITIONS.

This method will return null if the current content is not represented by a Scene.

TransitionManager! getContentTransitionManager()

Retrieve the TransitionManager responsible for default transitions in this window. Requires Window.FEATURE_CONTENT_TRANSITIONS.

This method will return non-null after content has been initialized (e.g. by using #setContentView) if Window.FEATURE_CONTENT_TRANSITIONS has been granted.

ComponentCaller getCurrentCaller()

Returns the ComponentCaller instance of the app that re-launched this activity with a new intent via #onNewIntent or #onActivityResult.

Note that this method only works within the #onNewIntent and #onActivityResult methods. If you call this method outside #onNewIntent and #onActivityResult, it will throw an IllegalStateException.

You can also retrieve the caller if you override onNewIntent(android.content.Intent,android.app.ComponentCaller) or onActivityResult(int,int,android.content.Intent,android.app.ComponentCaller).

To keep the ComponentCaller instance for future use, call setIntent(android.content.Intent,android.app.ComponentCaller), and use getCaller to retrieve it.

View? getCurrentFocus()

Calls android.view.Window#getCurrentFocus on the Window of this Activity to return the currently focused view.

FragmentManager! getFragmentManager()

Return the FragmentManager for interacting with fragments associated with this activity.

ComponentCaller getInitialCaller()

Returns the ComponentCaller instance of the app that initially launched this activity.

Note that calls to #onNewIntent and #setIntent have no effect on the returned value of this method.

Intent! getIntent()

Returns the intent that started this activity.

To keep the Intent instance for future use, call setIntent(android.content.Intent), and use this method to retrieve it.

Note that in #onNewIntent, this method will return the original Intent. You can use setIntent(android.content.Intent) to update it to the new Intent.

Any? getLastNonConfigurationInstance()

Retrieve the non-configuration instance data that was previously returned by onRetainNonConfigurationInstance(). This will be available from the initial #onCreate and onStart calls to the new instance, allowing you to extract any useful dynamic state from the previous instance.

Note that the data you retrieve here should only be used as an optimization for handling configuration changes. You should always be able to handle getting a null pointer back, and an activity must still be able to restore itself to its previous state (through the normal onSaveInstanceState(android.os.Bundle) mechanism) even if this function returns null.

Note: For most cases you should use the Fragment API Fragment.setRetainInstance(boolean) instead; this is also available on older platforms through the Android support libraries.

String? getLaunchedFromPackage()

Returns the package name of the app that initially launched this activity.

In order to receive the launching app's package name, at least one of the following has to be met:

  • The app must call ActivityOptions.setShareIdentityEnabled(boolean) with a value of true and launch this activity with the resulting ActivityOptions.
  • The launched activity has the same uid as the launching app.
  • The launched activity is running in a package that is signed with the same key used to sign the platform (typically only system packages such as Settings will meet this requirement).
. These are the same requirements for getLaunchedFromUid(); if any of these are met, then these methods can be used to obtain the uid and package name of the launching app. If none are met, then null is returned.

Note, even if the above conditions are not met, the launching app's identity may still be available from getCallingPackage() if this activity was started with Activity#startActivityForResult to allow validation of the result's recipient.

Int getLaunchedFromUid()

Returns the uid of the app that initially launched this activity.

In order to receive the launching app's uid, at least one of the following has to be met:

  • The app must call ActivityOptions.setShareIdentityEnabled(boolean) with a value of true and launch this activity with the resulting ActivityOptions.
  • The launched activity has the same uid as the launching app.
  • The launched activity is running in a package that is signed with the same key used to sign the platform (typically only system packages such as Settings will meet this requirement).
. These are the same requirements for getLaunchedFromPackage(); if any of these are met, then these methods can be used to obtain the uid and package name of the launching app. If none are met, then Process.INVALID_UID is returned.

Note, even if the above conditions are not met, the launching app's identity may still be available from getCallingPackage() if this activity was started with Activity#startActivityForResult to allow validation of the result's recipient.

LayoutInflater getLayoutInflater()

Convenience for calling android.view.Window#getLayoutInflater.

LoaderManager! getLoaderManager()

Return the LoaderManager for this activity, creating it if needed.

String getLocalClassName()

Returns class name for this activity with the package prefix removed. This is the default name used to read and write settings.

Int getMaxNumPictureInPictureActions()

Return the number of actions that will be displayed in the picture-in-picture UI when the user interacts with the activity currently in picture-in-picture mode. This number may change if the global configuration changes (ie. if the device is plugged into an external display), but will always be at least three.

MediaController! getMediaController()

Gets the controller which should be receiving media key and volume events while this activity is in the foreground.

MenuInflater getMenuInflater()

Returns a MenuInflater with this context.

OnBackInvokedDispatcher getOnBackInvokedDispatcher()

Returns the OnBackInvokedDispatcher instance associated with the window that this activity is attached to.

Activity! getParent()

Returns the parent Activity if this is a child Activity of an ActivityGroup.

Intent? getParentActivityIntent()

Obtain an Intent that will launch an explicit target activity specified by this activity's logical parent. The logical parent is named in the application's manifest by the parentActivityName attribute. Activity subclasses may override this method to modify the Intent returned by super.getParentActivityIntent() or to implement a different mechanism of retrieving the parent intent entirely.

SharedPreferences! getPreferences(mode: Int)

Retrieve a SharedPreferences object for accessing preferences that are private to this activity. This simply calls the underlying getSharedPreferences(java.lang.String,int) method by passing in this activity's class name as the preferences name.

Uri? getReferrer()

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

If called while inside the handling of #onNewIntent, this function will return the referrer that submitted that new intent to the activity only after setIntent(android.content.Intent) is called with the provided intent.

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

Int getRequestedOrientation()

Return the current requested orientation of the activity. This will either be the orientation requested in its component's manifest, or the last requested orientation given to setRequestedOrientation(int).

SearchEvent! getSearchEvent()

During the onSearchRequested() callbacks, this function will return the SearchEvent that triggered the callback, if it exists.

SplashScreen getSplashScreen()

Get the interface that activity use to talk to the splash screen.

Any! getSystemService(name: String)

Return the handle to a system-level service by name. The class of the returned object varies by the requested name. Currently available names are:

WINDOW_SERVICE ("window")
The top-level window manager in which you can place custom windows. The returned object is a android.view.WindowManager. Must only be obtained from a visual context such as Activity or a Context created with createWindowContext(int,android.os.Bundle), which are adjusted to the configuration and visual bounds of an area on screen.
LAYOUT_INFLATER_SERVICE ("layout_inflater")
A android.view.LayoutInflater for inflating layout resources in this context. Must only be obtained from a visual context such as Activity or a Context created with createWindowContext(int,android.os.Bundle), which are adjusted to the configuration and visual bounds of an area on screen.
ACTIVITY_SERVICE ("activity")
A android.app.ActivityManager for interacting with the global activity state of the system.
WALLPAPER_SERVICE ("wallpaper")
A android.service.wallpaper.WallpaperService for accessing wallpapers in this context. Must only be obtained from a visual context such as Activity or a Context created with createWindowContext(int,android.os.Bundle), which are adjusted to the configuration and visual bounds of an area on screen.
POWER_SERVICE ("power")
A android.os.PowerManager for controlling power management.
ALARM_SERVICE ("alarm")
A android.app.AlarmManager for receiving intents at the time of your choosing.
NOTIFICATION_SERVICE ("notification")
A android.app.NotificationManager for informing the user of background events.
KEYGUARD_SERVICE ("keyguard")
A android.app.KeyguardManager for controlling keyguard.
LOCATION_SERVICE ("location")
A android.location.LocationManager for controlling location (e.g., GPS) updates.
SEARCH_SERVICE ("search")
A android.app.SearchManager for handling search.
VIBRATOR_MANAGER_SERVICE ("vibrator_manager")
A android.os.VibratorManager for accessing the device vibrators, interacting with individual ones and playing synchronized effects on multiple vibrators.
VIBRATOR_SERVICE ("vibrator")
A android.os.Vibrator for interacting with the vibrator hardware.
CONNECTIVITY_SERVICE ("connectivity")
A ConnectivityManager for handling management of network connections.
IPSEC_SERVICE ("ipsec")
A IpSecManager for managing IPSec on sockets and networks.
WIFI_SERVICE ("wifi")
A WifiManager for management of Wi-Fi connectivity. On releases before Android 7, it should only be obtained from an application context, and not from any other derived context to avoid memory leaks within the calling process.
WIFI_AWARE_SERVICE ("wifiaware")
A WifiAwareManager for management of Wi-Fi Aware discovery and connectivity.
WIFI_P2P_SERVICE ("wifip2p")
A WifiP2pManager for management of Wi-Fi Direct connectivity.
INPUT_METHOD_SERVICE ("input_method")
An InputMethodManager for management of input methods.
UI_MODE_SERVICE ("uimode")
An android.app.UiModeManager for controlling UI modes.
DOWNLOAD_SERVICE ("download")
A android.app.DownloadManager for requesting HTTP downloads
BATTERY_SERVICE ("batterymanager")
A android.os.BatteryManager for managing battery state
JOB_SCHEDULER_SERVICE ("taskmanager")
A android.app.job.JobScheduler for managing scheduled tasks
NETWORK_STATS_SERVICE ("netstats")
A NetworkStatsManager for querying network usage statistics.
HARDWARE_PROPERTIES_SERVICE ("hardware_properties")
A android.os.HardwarePropertiesManager for accessing hardware properties.
DOMAIN_VERIFICATION_SERVICE ("domain_verification")
A android.content.pm.verify.domain.DomainVerificationManager for accessing web domain approval state.
DISPLAY_HASH_SERVICE ("display_hash")
A android.view.displayhash.DisplayHashManager for management of display hashes.
#AUTHENTICATION_POLICY_SERVICE ("authentication_policy")
A android.security.authenticationpolicy.AuthenticationPolicyManager for managing authentication related policies on the device.

Note: System services obtained via this API may be closely associated with the Context in which they are obtained from. In general, do not share the service objects between various different contexts (Activities, Applications, Services, Providers, etc.)

Note: Instant apps, for which PackageManager.isInstantApp() returns true, don't have access to the following system services: DEVICE_POLICY_SERVICE, FINGERPRINT_SERVICE, KEYGUARD_SERVICE, SHORTCUT_SERVICE, USB_SERVICE, WALLPAPER_SERVICE, WIFI_P2P_SERVICE, WIFI_SERVICE, WIFI_AWARE_SERVICE. For these services this method will return null. Generally, if you are running as an instant app you should always check whether the result of this method is null.

Note: When implementing this method, keep in mind that new services can be added on newer Android releases, so if you're looking for just the explicit names mentioned above, make sure to return null when you don't recognize the name — if you throw a RuntimeException exception instead, your app might break on new Android releases.

Int getTaskId()

Return the identifier of the task this activity is in. This identifier will remain the same for the lifetime of the activity.

CharSequence! getTitle()

Int getTitleColor()

VoiceInteractor! getVoiceInteractor()

Retrieve the active VoiceInteractor that the user is going through to interact with this activity.

Int getVolumeControlStream()

Gets the suggested audio stream whose volume should be changed by the hardware volume controls.

Window! getWindow()

Retrieve the current android.view.Window for the activity. This can be used to directly access parts of the Window API that are not available through Activity/Screen.

WindowManager! getWindowManager()

Retrieve the window manager for showing custom windows.

Boolean hasWindowFocus()

Returns true if this activity's main window currently has window focus. Note that this is not the same as the view itself having focus.

Unit invalidateOptionsMenu()

Declare that the options menu has changed, so should be recreated. The onCreateOptionsMenu(android.view.Menu) method will be called the next time it needs to be displayed.

Boolean isActivityTransitionRunning()

Returns whether there are any activity transitions currently running on this activity. A return value of true can mean that either an enter or exit transition is running, including whether the background of the activity is animating as a part of that transition.

Boolean isChangingConfigurations()

Check to see whether this activity is in the process of being destroyed in order to be recreated with a new configuration. This is often used in onStop to determine whether the state needs to be cleaned up or will be passed on to the next instance of the activity via onRetainNonConfigurationInstance().

Boolean isChild()

Whether this is a child Activity of an ActivityGroup.

Boolean isDestroyed()

Returns true if the final onDestroy() call has been made on the Activity, so this instance is now dead.

Boolean isFinishing()

Check to see whether this activity is in the process of finishing, either because you called finish on it or someone else has requested that it finished. This is often used in onPause to determine whether the activity is simply pausing or completely finishing.

Boolean isImmersive()

Bit indicating that this activity is "immersive" and should not be interrupted by notifications if possible. This value is initially set by the manifest property android:immersive but may be changed at runtime by setImmersive.

Boolean isInMultiWindowMode()

Returns true if the activity is currently in multi-window mode.

Boolean isInPictureInPictureMode()

Returns true if the activity is currently in picture-in-picture mode.

Boolean isLaunchedFromBubble()

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

Boolean isLocalVoiceInteractionSupported()

Queries whether the currently enabled voice interaction service supports returning a voice interactor for use by the activity. This is valid only for the duration of the activity.

Boolean isTaskRoot()

Return whether this activity is the root of a task. The root is the first activity in a task.

Boolean isVoiceInteraction()

Check whether this activity is running as part of a voice interaction with the user. If true, it should perform its interaction with the user through the VoiceInteractor returned by getVoiceInteractor.

Boolean isVoiceInteractionRoot()

Like isVoiceInteraction, but only returns true if this is also the root of a voice interaction. That is, returns true if this activity was directly started by the voice interaction service as the initiation of a voice interaction. Otherwise, for example if it was started by another activity while under voice interaction, returns false. If the activity launchMode is singleTask, it forces the activity to launch in a new task, separate from the one that started it. Therefore, there is no longer a relationship between them, and isVoiceInteractionRoot() return false in this case.

Cursor! managedQuery(uri: Uri!, projection: Array<String!>!, selection: String!, selectionArgs: Array<String!>!, sortOrder: String!)

Wrapper around ContentResolver.query(android.net.Uri , String[], String, String[], String) that gives the resulting Cursor to call startManagingCursor so that the activity will manage its lifecycle for you. If you are targeting android.os.Build.VERSION_CODES#HONEYCOMB or later, consider instead using LoaderManager instead, available via getLoaderManager().

Warning: Do not call android.database.Cursor#close() on a cursor obtained using this method, because the activity will do that for you at the appropriate time. However, if you call stopManagingCursor on a cursor from a managed query, the system will not automatically close the cursor and, in that case, you must call android.database.Cursor#close().

Boolean moveTaskToBack(nonRoot: Boolean)

Move the task containing this activity to the back of the activity stack. The activity's order within the task is unchanged.

Boolean navigateUpTo(upIntent: Intent!)

Navigate from this activity to the activity specified by upIntent, finishing this activity in the process. If the activity indicated by upIntent already exists in the task's history, this activity and all others before the indicated activity in the history stack will be finished.

If the indicated activity does not appear in the history stack, this will finish each activity in this task until the root activity of the task is reached, resulting in an "in-app home" behavior. This can be useful in apps with a complex navigation hierarchy when an activity may be reached by a path not passing through a canonical parent activity.

This method should be used when performing up navigation from within the same task as the destination. If up navigation should cross tasks in some cases, see shouldUpRecreateTask(android.content.Intent).

Boolean navigateUpToFromChild(child: Activity!, upIntent: Intent!)

This is called when a child activity of this one calls its navigateUpTo method. The default implementation simply calls navigateUpTo(upIntent) on this activity (the parent).

Unit onActionModeFinished(mode: ActionMode!)

Notifies the activity that an action mode has finished. Activity subclasses overriding this method should call the superclass implementation.
If you override this method you must call through to the superclass implementation.

Unit onActionModeStarted(mode: ActionMode!)

Notifies the Activity that an action mode has been started. Activity subclasses overriding this method should call the superclass implementation.
If you override this method you must call through to the superclass implementation.

Unit onActivityReenter(resultCode: Int, data: Intent!)

Called when an activity you launched with an activity transition exposes this Activity through a returning activity transition, giving you the resultCode and any additional data from it. This method will only be called if the activity set a result code other than RESULT_CANCELED and it supports activity transitions with Window.FEATURE_ACTIVITY_TRANSITIONS.

The purpose of this function is to let the called Activity send a hint about its state so that this underlying Activity can prepare to be exposed. A call to this method does not guarantee that the called Activity has or will be exiting soon. It only indicates that it will expose this Activity's Window and it has some data to pass to prepare it.

Unit onActivityResult(requestCode: Int, resultCode: Int, data: Intent!)

Called when an activity you launched exits, giving you the requestCode you started it with, the resultCode it returned, and any additional data from it. The resultCode will be RESULT_CANCELED if the activity explicitly returned that, didn't return any result, or crashed during its operation.

An activity can never receive a result in the resumed state. You can count on onResume being called after this method, though not necessarily immediately after. If the activity was resumed, it will be paused and the result will be delivered, followed by onResume. If the activity wasn't in the resumed state, then the result will be delivered, with onResume called sometime later when the activity becomes active again.

This method is never invoked if your activity sets noHistory to true.

Unit onActivityResult(requestCode: Int, resultCode: Int, data: Intent?, caller: ComponentCaller)

Same as onActivityResult(int,int,android.content.Intent), but with an extra parameter for the ComponentCaller instance associated with the app that sent the result.

If you want to retrieve the caller without overriding this method, call getCurrentCaller inside your existing onActivityResult(int,int,android.content.Intent).

Note that you should only override one #onActivityResult method.

Unit onApplyThemeResource(theme: Resources.Theme!, resid: Int, first: Boolean)

Unit onAttachFragment(fragment: Fragment!)

Called when a Fragment is being attached to this activity, immediately after the call to its android.app.Fragment#onAttach method and before Fragment.onCreate().

Unit onAttachedToWindow()

Called when the main window associated with the activity has been attached to the window manager. See View.onAttachedToWindow() for more information.

Unit onBackPressed()

Called when the activity has detected the user's press of the back key. The default implementation depends on the platform version:

Unit onChildTitleChanged(childActivity: Activity!, title: CharSequence!)

Unit onConfigurationChanged(newConfig: Configuration)

Called by the system when the device configuration changes while your activity is running. Note that this will only be called if you have selected configurations you would like to handle with the android.R.attr#configChanges attribute in your manifest. If any configuration change occurs that is not selected to be reported by that attribute, then instead of reporting it the system will stop and restart the activity (to have it launched with the new configuration). The only exception is if a size-based configuration is not large enough to be considered significant, in which case the system will not recreate the activity and will instead call this method. For details on this see the documentation on size-based config change.

At the time that this function has been called, your Resources object will have been updated to return resource values matching the new configuration.

Boolean onContextItemSelected(item: MenuItem)

This hook is called whenever an item in a context menu is selected. The default implementation simply returns false to have the normal processing happen (calling the item's Runnable or sending a message to its Handler as appropriate). You can use this method for any items for which you would like to do processing without those other facilities.

Use MenuItem.getMenuInfo() to get extra information set by the View that added this menu item.

Derived classes should call through to the base class for it to perform the default menu handling.

Unit onContextMenuClosed(menu: Menu)

This hook is called whenever the context menu is being closed (either by the user canceling the menu with the back/menu button, or when an item is selected).

Unit onCreate(savedInstanceState: Bundle?)

Called when the activity is starting. This is where most initialization should go: calling setContentView(int) to inflate the activity's UI, using findViewById to programmatically interact with widgets in the UI, calling managedQuery(android.net.Uri,java.lang.String[],java.lang.String,java.lang.String[],java.lang.String) to retrieve cursors for data being displayed, etc.

You can call finish from within this function, in which case onDestroy() will be immediately called after #onCreate without any of the rest of the activity lifecycle (onStart, onResume, onPause, etc) executing.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.


This method must be called from the main thread of your app.
If you override this method you must call through to the superclass implementation.

Unit onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?)

Same as onCreate(android.os.Bundle) but called for those activities created with the attribute android.R.attr#persistableMode set to persistAcrossReboots.

Unit onCreateContextMenu(menu: ContextMenu!, v: View!, menuInfo: ContextMenu.ContextMenuInfo!)

Called when a context menu for the view is about to be shown. Unlike onCreateOptionsMenu(android.view.Menu), this will be called every time the context menu is about to be shown and should be populated for the view (or item inside the view for AdapterView subclasses, this can be found in the menuInfo)).

Use onContextItemSelected(android.view.MenuItem) to know when an item has been selected.

It is not safe to hold onto the context menu after this method returns.

CharSequence? onCreateDescription()

Generate a new description for this activity. This method is called before stopping the activity and can, if desired, return some textual description of its current state to be displayed to the user.

The default implementation returns null, which will cause you to inherit the description from the previous activity. If all activities return null, generally the label of the top activity will be used as the description.

Dialog! onCreateDialog(id: Int)

Dialog? onCreateDialog(id: Int, args: Bundle!)

Callback for creating dialogs that are managed (saved and restored) for you by the activity. The default implementation calls through to onCreateDialog(int) for compatibility. If you are targeting android.os.Build.VERSION_CODES#HONEYCOMB or later, consider instead using a DialogFragment instead.

If you use showDialog(int), the activity will call through to this method the first time, and hang onto it thereafter. Any dialog that is created by this method will automatically be saved and restored for you, including whether it is showing.

If you would like the activity to manage saving and restoring dialogs for you, you should override this method and handle any ids that are passed to #showDialog.

If you would like an opportunity to prepare your dialog before it is shown, override onPrepareDialog(int,android.app.Dialog,android.os.Bundle).

Unit onCreateNavigateUpTaskStack(builder: TaskStackBuilder!)

Define the synthetic task stack that will be generated during Up navigation from a different task.

The default implementation of this method adds the parent chain of this activity as specified in the manifest to the supplied TaskStackBuilder. Applications may choose to override this method to construct the desired task stack in a different way.

This method will be invoked by the default implementation of onNavigateUp() if shouldUpRecreateTask(android.content.Intent) returns true when supplied with the intent returned by getParentActivityIntent().

Applications that wish to supply extra Intent parameters to the parent stack defined by the manifest should override onPrepareNavigateUpTaskStack(android.app.TaskStackBuilder).

Boolean onCreateOptionsMenu(menu: Menu!)

Initialize the contents of the Activity's standard options menu. You should place your menu items in to menu.

This is only called once, the first time the options menu is displayed. To update the menu every time it is displayed, see onPrepareOptionsMenu.

The default implementation populates the menu with standard system menu items. These are placed in the Menu.CATEGORY_SYSTEM group so that they will be correctly ordered with application-defined menu items. Deriving classes should always call through to the base implementation.

You can safely hold on to menu (and any items created from it), making modifications to it as desired, until the next time onCreateOptionsMenu() is called.

When you add items to the menu, you can implement the Activity's onOptionsItemSelected method to handle them there.

Boolean onCreatePanelMenu(featureId: Int, menu: Menu)

Default implementation of android.view.Window.Callback#onCreatePanelMenu for activities. This calls through to the new onCreateOptionsMenu method for the android.view.Window#FEATURE_OPTIONS_PANEL panel, so that subclasses of Activity don't need to deal with feature codes.

View? onCreatePanelView(featureId: Int)

Default implementation of android.view.Window.Callback#onCreatePanelView for activities. This simply returns null so that all panel sub-windows will have the default menu behavior.

Boolean onCreateThumbnail(outBitmap: Bitmap!, canvas: Canvas!)

View? onCreateView(parent: View?, name: String, context: Context, attrs: AttributeSet)

Standard implementation of android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet) used when inflating with the LayoutInflater returned by #getSystemService. This implementation handles tags to embed fragments inside of the activity.

View? onCreateView(name: String, context: Context, attrs: AttributeSet)

Standard implementation of android.view.LayoutInflater.Factory#onCreateView used when inflating with the LayoutInflater returned by #getSystemService. This implementation does nothing and is for pre-android.os.Build.VERSION_CODES#HONEYCOMB apps. Newer apps should use onCreateView(android.view.View,java.lang.String,android.content.Context,android.util.AttributeSet).

Unit onDetachedFromWindow()

Called when the main window associated with the activity has been detached from the window manager. See View.onDetachedFromWindow() for more information.

Unit onEnterAnimationComplete()

Activities cannot draw during the period that their windows are animating in. In order to know when it is safe to begin drawing they can override this method which will be called when the entering animation has completed.

Boolean onGenericMotionEvent(event: MotionEvent!)

Called when a generic motion event was not handled by any of the views inside of the activity.

Generic motion events describe joystick movements, hover events from mouse or stylus devices, trackpad touches, scroll wheel movements and other motion events not handled by onTouchEvent(android.view.MotionEvent) or onTrackballEvent(android.view.MotionEvent). The source of the motion event specifies the class of input that was received. Implementations of this method must examine the bits in the source before processing the event.

Generic motion events with source class android.view.InputDevice#SOURCE_CLASS_POINTER are delivered to the view under the pointer. All other generic motion events are delivered to the focused view.

See View.onGenericMotionEvent(MotionEvent) for an example of how to handle this event.

Unit onGetDirectActions(cancellationSignal: CancellationSignal, callback: Consumer<MutableList<DirectAction!>!>)

Returns the list of direct actions supported by the app.

You should return the list of actions that could be executed in the current context, which is in the current state of the app. If the actions that could be executed by the app changes you should report that via calling VoiceInteractor.notifyDirectActionsChanged().

To get the voice interactor you need to call getVoiceInteractor() which would return non null only if there is an ongoing voice interaction session. You can also detect when the voice interactor is no longer valid because the voice interaction session that is backing is finished by calling VoiceInteractor.registerOnDestroyedCallback(Executor, Runnable).

This method will be called only after onStart() and before onStop().

You should pass to the callback the currently supported direct actions which cannot be null or contain null elements.

You should return the action list as soon as possible to ensure the consumer, for example the assistant, is as responsive as possible which would improve user experience of your app.

Boolean onKeyDown(keyCode: Int, event: KeyEvent!)

Called when a key was pressed down and not handled by any of the views inside of the activity. So, for example, key presses while the cursor is inside a TextView will not trigger the event (unless it is a navigation to another object) because TextView handles its own key presses.

If the focused view didn't want this event, this method is called.

The default implementation takes care of KeyEvent.KEYCODE_BACK by calling onBackPressed(), though the behavior varies based on the application compatibility mode: for android.os.Build.VERSION_CODES#ECLAIR or later applications, it will set up the dispatch to call onKeyUp where the action will be performed; for earlier applications, it will perform the action immediately in on-down, as those versions of the platform behaved. This implementation will also take care of KeyEvent.KEYCODE_ESCAPE by finishing the activity if it would be closed by touching outside of it.

Other additional default key handling may be performed if configured with setDefaultKeyMode.

Boolean onKeyLongPress(keyCode: Int, event: KeyEvent!)

Default implementation of KeyEvent.Callback.onKeyLongPress(): always returns false (doesn't handle the event). To receive this callback, you must return true from onKeyDown for the current event stream.

Boolean onKeyMultiple(keyCode: Int, repeatCount: Int, event: KeyEvent!)

Default implementation of KeyEvent.Callback.onKeyMultiple(): always returns false (doesn't handle the event).

Boolean onKeyShortcut(keyCode: Int, event: KeyEvent!)

Called when a key shortcut event is not handled by any of the views in the Activity. Override this method to implement global key shortcuts for the Activity. Key shortcuts can also be implemented by setting the shortcut property of menu items.

Boolean onKeyUp(keyCode: Int, event: KeyEvent!)

Called when a key was released and not handled by any of the views inside of the activity. So, for example, key presses while the cursor is inside a TextView will not trigger the event (unless it is a navigation to another object) because TextView handles its own key presses.

The default implementation handles KEYCODE_BACK to stop the activity and go back.

Unit onLocalVoiceInteractionStarted()

Callback to indicate that startLocalVoiceInteraction(android.os.Bundle) has resulted in a voice interaction session being started. You can now retrieve a voice interactor using getVoiceInteractor().

Unit onLocalVoiceInteractionStopped()

Callback to indicate that the local voice interaction has stopped either because it was requested through a call to stopLocalVoiceInteraction() or because it was canceled by the user. The previously acquired VoiceInteractor is no longer valid after this.

Unit onLowMemory()

Boolean onMenuItemSelected(featureId: Int, item: MenuItem)

Default implementation of android.view.Window.Callback#onMenuItemSelected for activities. This calls through to the new onOptionsItemSelected method for the android.view.Window#FEATURE_OPTIONS_PANEL panel, so that subclasses of Activity don't need to deal with feature codes.

Boolean onMenuOpened(featureId: Int, menu: Menu)

Called when a panel's menu is opened by the user. This may also be called when the menu is changing from one type to another (for example, from the icon menu to the expanded menu).

Unit onMultiWindowModeChanged(isInMultiWindowMode: Boolean)

Called by the system when the activity changes from fullscreen mode to multi-window mode and visa-versa.

Unit onMultiWindowModeChanged(isInMultiWindowMode: Boolean, newConfig: Configuration!)

Called by the system when the activity changes from fullscreen mode to multi-window mode and visa-versa. This method provides the same configuration that will be sent in the following onConfigurationChanged(android.content.res.Configuration) call after the activity enters this mode.

Boolean onNavigateUp()

This method is called whenever the user chooses to navigate Up within your application's activity hierarchy from the action bar.

If the attribute parentActivityName was specified in the manifest for this activity or an activity-alias to it, default Up navigation will be handled automatically. If any activity along the parent chain requires extra Intent arguments, the Activity subclass should override the method onPrepareNavigateUpTaskStack(android.app.TaskStackBuilder) to supply those arguments.

See Tasks and Back Stack from the developer guide and Navigation from the design guide for more information about navigating within your app.

See the TaskStackBuilder class and the Activity methods getParentActivityIntent(), shouldUpRecreateTask(android.content.Intent), and navigateUpTo(android.content.Intent) for help implementing custom Up navigation. The AppNavigation sample application in the Android SDK is also available for reference.

Boolean onNavigateUpFromChild(child: Activity!)

This is called when a child activity of this one attempts to navigate up. The default implementation simply calls onNavigateUp() on this activity (the parent).

Unit onNewIntent(intent: Intent!)

This is called for activities that set launchMode to "singleTop" in their package, or if a client used the Intent.FLAG_ACTIVITY_SINGLE_TOP flag when calling #startActivity. In either case, when the activity is re-launched while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be called on the existing instance with the Intent that was used to re-launch it.

An activity can never receive a new intent in the resumed state. You can count on onResume being called after this method, though not necessarily immediately after the completion of this callback. If the activity was resumed, it will be paused and new intent will be delivered, followed by onResume. If the activity wasn't in the resumed state, then new intent can be delivered immediately, with onResume() called sometime later when activity becomes active again.

Note that getIntent still returns the original Intent. You can use setIntent(android.content.Intent) to update it to this new Intent.

Unit onNewIntent(intent: Intent, caller: ComponentCaller)

Same as onNewIntent(android.content.Intent), but with an extra parameter for the ComponentCaller instance associated with the app that sent the intent.

If you want to retrieve the caller without overriding this method, call getCurrentCaller inside your existing onNewIntent(android.content.Intent).

Note that you should only override one #onNewIntent method.

Boolean onOptionsItemSelected(item: MenuItem)

This hook is called whenever an item in your options menu is selected. The default implementation simply returns false to have the normal processing happen (calling the item's Runnable or sending a message to its Handler as appropriate). You can use this method for any items for which you would like to do processing without those other facilities.

Derived classes should call through to the base class for it to perform the default menu handling.

Unit onOptionsMenuClosed(menu: Menu!)

This hook is called whenever the options menu is being closed (either by the user canceling the menu with the back/menu button, or when an item is selected).

Unit onPanelClosed(featureId: Int, menu: Menu)

Default implementation of android.view.Window.Callback#onPanelClosed(int, Menu) for activities. This calls through to onOptionsMenuClosed(android.view.Menu) method for the android.view.Window#FEATURE_OPTIONS_PANEL panel, so that subclasses of Activity don't need to deal with feature codes. For context menus (Window.FEATURE_CONTEXT_MENU), the onContextMenuClosed(android.view.Menu) will be called.

Unit onPause()

Called as part of the activity lifecycle when the user no longer actively interacts with the activity, but it is still visible on screen. The counterpart to onResume.

When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause returns, so be sure to not do anything lengthy here.

This callback is mostly used for saving any persistent state the activity is editing, to present a "edit in place" model to the user and making sure nothing is lost if there are not enough resources to start the new activity without first killing this one. This is also a good place to stop things that consume a noticeable amount of CPU in order to make the switch to the next activity as fast as possible.

On platform versions prior to android.os.Build.VERSION_CODES#Q this is also a good place to try to close exclusive-access devices or to release access to singleton resources. Starting with android.os.Build.VERSION_CODES#Q there can be multiple resumed activities in the system at the same time, so onTopResumedActivityChanged(boolean) should be used for that purpose instead.

If an activity is launched on top, after receiving this call you will usually receive a following call to onStop (after the next activity has been resumed and displayed above). However in some cases there will be a direct call back to onResume without going through the stopped state. An activity can also rest in paused state in some cases when in multi-window mode, still visible to user.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.


If you override this method you must call through to the superclass implementation.

Unit onPerformDirectAction(actionId: String, arguments: Bundle, cancellationSignal: CancellationSignal, resultListener: Consumer<Bundle!>)

This is called to perform an action previously defined by the app. Apps also have access to getVoiceInteractor() to follow up on the action.

Unit onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean)

Called by the system when the activity changes to and from picture-in-picture mode.

Unit onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration!)

Called by the system when the activity changes to and from picture-in-picture mode. This method provides the same configuration that will be sent in the following onConfigurationChanged(android.content.res.Configuration) call after the activity enters this mode.

Boolean onPictureInPictureRequested()

This method is called by the system in various cases where picture in picture mode should be entered if supported.

It is up to the app developer to choose whether to call enterPictureInPictureMode(android.app.PictureInPictureParams) at this time. For example, the system will call this method when the activity is being put into the background, so the app developer might want to switch an activity into PIP mode instead.

Unit onPictureInPictureUiStateChanged(pipState: PictureInPictureUiState)

Called by the system when the activity is in PiP and has state changes. Compare to onPictureInPictureModeChanged(boolean,android.content.res.Configuration), which is only called when PiP mode changes (meaning, enters or exits PiP), this can be called at any time while the activity is in PiP mode. Therefore, all invocation can only happen after onPictureInPictureModeChanged(boolean,android.content.res.Configuration) is called with true, and before onPictureInPictureModeChanged(boolean,android.content.res.Configuration) is called with false. You would not need to worry about cases where this is called and the activity is not in Picture-In-Picture mode. For managing cases where the activity enters/exits Picture-in-Picture (e.g. resources clean-up on exit), use onPictureInPictureModeChanged(boolean,android.content.res.Configuration). The default state is everything declared in PictureInPictureUiState is false, such as PictureInPictureUiState.isStashed().

Unit onPostCreate(savedInstanceState: Bundle?)

Called when activity start-up is complete (after onStart and #onRestoreInstanceState have been called). Applications will generally not implement this method; it is intended for system classes to do final initialization after application code has run.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.


If you override this method you must call through to the superclass implementation.

Unit onPostCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?)

This is the same as onPostCreate(android.os.Bundle) but is called for activities created with the attribute android.R.attr#persistableMode set to persistAcrossReboots.

Unit onPostResume()

Called when activity resume is complete (after onResume has been called). Applications will generally not implement this method; it is intended for system classes to do final setup after application resume code has run.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.


If you override this method you must call through to the superclass implementation.

Unit onPrepareDialog(id: Int, dialog: Dialog!)

Unit onPrepareDialog(id: Int, dialog: Dialog!, args: Bundle!)

Provides an opportunity to prepare a managed dialog before it is being shown. The default implementation calls through to onPrepareDialog(int,android.app.Dialog) for compatibility.

Override this if you need to update a managed dialog based on the state of the application each time it is shown. For example, a time picker dialog might want to be updated with the current time. You should call through to the superclass's implementation. The default implementation will set this Activity as the owner activity on the Dialog.

Unit onPrepareNavigateUpTaskStack(builder: TaskStackBuilder!)

Prepare the synthetic task stack that will be generated during Up navigation from a different task.

This method receives the TaskStackBuilder with the constructed series of Intents as generated by onCreateNavigateUpTaskStack(android.app.TaskStackBuilder). If any extra data should be added to these intents before launching the new task, the application should override this method and add that data here.

Boolean onPrepareOptionsMenu(menu: Menu!)

Prepare the Screen's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.

The default implementation updates the system menu items based on the activity's state. Deriving classes should always call through to the base class implementation.

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

Default implementation of android.view.Window.Callback#onPreparePanel for activities. This calls through to the new onPrepareOptionsMenu method for the android.view.Window#FEATURE_OPTIONS_PANEL panel, so that subclasses of Activity don't need to deal with feature codes.

Unit onProvideAssistContent(outContent: AssistContent!)

This is called when the user is requesting an assist, to provide references to content related to the current activity. Before being called, the outContent Intent is filled with the base Intent of the activity (the Intent returned by getIntent()). The Intent's extras are stripped of any types that are not valid for PersistableBundle or non-framework Parcelables, and the flags Intent.FLAG_GRANT_WRITE_URI_PERMISSION and Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION are cleared from the Intent.

Custom implementation may adjust the content intent to better reflect the top-level context of the activity, and fill in its ClipData with additional content of interest that the user is currently viewing. For example, an image gallery application that has launched in to an activity allowing the user to swipe through pictures should modify the intent to reference the current image they are looking it; such an application when showing a list of pictures should add a ClipData that has references to all of the pictures currently visible on screen.

Unit onProvideAssistData(data: Bundle!)

This is called when the user is requesting an assist, to build a full Intent.ACTION_ASSIST Intent with all of the context of the current application. You can override this method to place into the bundle anything you would like to appear in the Intent.EXTRA_ASSIST_CONTEXT part of the assist Intent.

This function will be called after any global assist callbacks that had been registered with Application.registerOnProvideAssistDataListener.

Unit onProvideKeyboardShortcuts(data: MutableList<KeyboardShortcutGroup!>!, menu: Menu?, deviceId: Int)

Uri! onProvideReferrer()

Override to generate the desired referrer for the content currently being shown by the app. The default implementation returns null, meaning the referrer will simply be the android-app: of the package name of this activity. Return a non-null Uri to have that supplied as the Intent.EXTRA_REFERRER of any activities started from it.

Unit onRequestPermissionsResult(requestCode: Int, permissions: Array<String!>, grantResults: IntArray)

Callback for the result from requesting permissions. This method is invoked for every call on #requestPermissions

Note: It is possible that the permissions request interaction with the user is interrupted. In this case you will receive empty permissions and results arrays which should be treated as a cancellation.

Unit onRequestPermissionsResult(requestCode: Int, permissions: Array<String!>, grantResults: IntArray, deviceId: Int)

Callback for the result from requesting permissions. This method is invoked for every call on #requestPermissions.

Note: It is possible that the permissions request interaction with the user is interrupted. In this case you will receive empty permissions and results arrays which should be treated as a cancellation.

Unit onRestart()

Called after onStop when the current activity is being re-displayed to the user (the user has navigated back to it). It will be followed by onStart and then onResume.

For activities that are using raw Cursor objects (instead of creating them through managedQuery(android.net.Uri,java.lang.String[],java.lang.String,java.lang.String[],java.lang.String), this is usually the place where the cursor should be requeried (because you had deactivated it in onStop.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.


If you override this method you must call through to the superclass implementation.

Unit onRestoreInstanceState(savedInstanceState: Bundle?, persistentState: PersistableBundle?)

This is the same as onRestoreInstanceState(android.os.Bundle) but is called for activities created with the attribute android.R.attr#persistableMode set to persistAcrossReboots. The android.os.PersistableBundle passed came from the restored PersistableBundle first saved in onSaveInstanceState(android.os.Bundle,android.os.PersistableBundle).

This method is called between onStart and #onPostCreate.

If this method is called onRestoreInstanceState(android.os.Bundle) will not be called.

At least one of savedInstanceState or persistentState will not be null.

Unit onResume()

Called after #onRestoreInstanceState, onRestart, or onPause. This is usually a hint for your activity to start interacting with the user, which is a good indicator that the activity became active and ready to receive input. This sometimes could also be a transit state toward another resting state. For instance, an activity may be relaunched to onPause due to configuration changes and the activity was visible, but wasn't the top-most activity of an activity task. onResume is guaranteed to be called before onPause in this case which honors the activity lifecycle policy and the activity eventually rests in onPause.

On platform versions prior to android.os.Build.VERSION_CODES#Q this is also a good place to try to open exclusive-access devices or to get access to singleton resources. Starting with android.os.Build.VERSION_CODES#Q there can be multiple resumed activities in the system simultaneously, so onTopResumedActivityChanged(boolean) should be used for that purpose instead.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.


If you override this method you must call through to the superclass implementation.

Any! onRetainNonConfigurationInstance()

Called by the system, as part of destroying an activity due to a configuration change, when it is known that a new instance will immediately be created for the new configuration. You can return any object you like here, including the activity instance itself, which can later be retrieved by calling getLastNonConfigurationInstance() in the new activity instance. If you are targeting android.os.Build.VERSION_CODES#HONEYCOMB or later, consider instead using a Fragment with Fragment.setRetainInstance(boolean.

This function is called purely as an optimization, and you must not rely on it being called. When it is called, a number of guarantees will be made to help optimize configuration switching:

  • The function will be called between onStop and onDestroy.
  • A new instance of the activity will always be immediately created after this one's onDestroy() is called. In particular, no messages will be dispatched during this time (when the returned object does not have an activity to be associated with).
  • The object you return here will always be available from the getLastNonConfigurationInstance() method of the following activity instance as described there.

These guarantees are designed so that an activity can use this API to propagate extensive state from the old to new activity instance, from loaded bitmaps, to network connections, to evenly actively running threads. Note that you should not propagate any data that may change based on the configuration, including any data loaded from resources such as strings, layouts, or drawables.

The guarantee of no message handling during the switch to the next activity simplifies use with active objects. For example if your retained state is an android.os.AsyncTask you are guaranteed that its call back functions (like android.os.AsyncTask#onPostExecute) will not be called from the call here until you execute the next instance's onCreate(android.os.Bundle). (Note however that there is of course no such guarantee for android.os.AsyncTask#doInBackground since that is running in a separate thread.)

Note: For most cases you should use the Fragment API Fragment.setRetainInstance(boolean) instead; this is also available on older platforms through the Android support libraries.

Unit onSaveInstanceState(outState: Bundle)

Called to retrieve per-instance state from an activity before being killed so that the state can be restored in #onCreate or #onRestoreInstanceState (the Bundle populated by this method will be passed to both).

This method is called before an activity may be killed so that when it comes back some time in the future it can restore its state. For example, if activity B is launched in front of activity A, and at some point activity A is killed to reclaim resources, activity A will have a chance to save the current state of its user interface via this method so that when the user returns to activity A, the state of the user interface can be restored via #onCreate or #onRestoreInstanceState.

Do not confuse this method with activity lifecycle callbacks such as onPause, which is always called when the user no longer actively interacts with an activity, or onStop which is called when activity becomes invisible. One example of when onPause and onStop is called and not this method is when a user navigates back from activity B to activity A: there is no need to call #onSaveInstanceState on B because that particular instance will never be restored, so the system avoids calling it. An example when onPause is called and not #onSaveInstanceState is when activity B is launched in front of activity A: the system may avoid calling #onSaveInstanceState on activity A if it isn't killed during the lifetime of B since the state of the user interface of A will stay intact.

The default implementation takes care of most of the UI per-instance state for you by calling android.view.View#onSaveInstanceState() on each view in the hierarchy that has an id, and by saving the id of the currently focused view (all of which is restored by the default implementation of #onRestoreInstanceState). If you override this method to save additional information not captured by each individual view, you will likely want to call through to the default implementation, otherwise be prepared to save all of the state of each view yourself.

If called, this method will occur after onStop for applications targeting platforms starting with android.os.Build.VERSION_CODES#P. For applications targeting earlier platform versions this method will occur before onStop and there are no guarantees about whether it will occur before or after onPause.

Unit onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle)

This is the same as #onSaveInstanceState but is called for activities created with the attribute android.R.attr#persistableMode set to persistAcrossReboots. The android.os.PersistableBundle passed in will be saved and presented in onCreate(android.os.Bundle,android.os.PersistableBundle) the first time that this activity is restarted following the next device reboot.

Boolean onSearchRequested()

Boolean onSearchRequested(searchEvent: SearchEvent?)

This hook is called when the user signals the desire to start a search.

You can use this function as a simple way to launch the search UI, in response to a menu item, search button, or other widgets within your activity. Unless overridden, calling this function is the same as calling startSearch(null,false,null,false), which launches search for the current activity as specified in its manifest, see SearchManager.

You can override this function to force global search, e.g. in response to a dedicated search key, or to block search entirely (by simply returning false).

Note: when running in a Configuration.UI_MODE_TYPE_TELEVISION or Configuration.UI_MODE_TYPE_WATCH, the default implementation changes to simply return false and you must supply your own custom implementation if you want to support search.

Unit onStart()

Called after #onCreate — or after onRestart when the activity had been stopped, but is now again being displayed to the user. It will usually be followed by onResume. This is a good place to begin drawing visual elements, running animations, etc.

You can call finish from within this function, in which case onStop will be immediately called after onStart without the lifecycle transitions in-between (onResume, onPause, etc) executing.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.


If you override this method you must call through to the superclass implementation.

Unit onStateNotSaved()

Called when an onResume is coming up, prior to other pre-resume callbacks such as #onNewIntent and #onActivityResult. This is primarily intended to give the activity a hint that its state is no longer saved -- it will generally be called after #onSaveInstanceState and prior to the activity being resumed/started again.

Unit onStop()

Called when you are no longer visible to the user. You will next receive either onRestart, onDestroy, or nothing, depending on later user activity. This is a good place to stop refreshing UI, running animations and other visual things.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.


If you override this method you must call through to the superclass implementation.

Unit onTitleChanged(title: CharSequence!, color: Int)

Unit onTopResumedActivityChanged(isTopResumedActivity: Boolean)

Called when activity gets or loses the top resumed position in the system.

Starting with android.os.Build.VERSION_CODES#Q multiple activities can be resumed at the same time in multi-window and multi-display modes. This callback should be used instead of onResume() as an indication that the activity can try to open exclusive-access devices like camera.

It will always be delivered after the activity was resumed and before it is paused. In some cases it might be skipped and activity can go straight from onResume() to onPause() without receiving the top resumed state.

Boolean onTouchEvent(event: MotionEvent!)

Called when a touch screen event was not handled by any of the views inside of the activity. This is most useful to process touch events that happen outside of your window bounds, where there is no view to receive it.

Boolean onTrackballEvent(event: MotionEvent!)

Called when the trackball was moved and not handled by any of the views inside of the activity. So, for example, if the trackball moves while focus is on a button, you will receive a call here because buttons do not normally do anything with trackball events. The call here happens before trackball movements are converted to DPAD key events, which then get sent back to the view hierarchy, and will be processed at the point for things like focus navigation.

Unit onTrimMemory(level: Int)

Unit onUserInteraction()

Called whenever a key, touch, or trackball event is dispatched to the activity. Implement this method if you wish to know that the user has interacted with the device in some way while your activity is running. This callback and onUserLeaveHint are intended to help activities manage status bar notifications intelligently; specifically, for helping activities determine the proper time to cancel a notification.

All calls to your activity's onUserLeaveHint callback will be accompanied by calls to onUserInteraction. This ensures that your activity will be told of relevant user activity such as pulling down the notification pane and touching an item there.

Note that this callback will be invoked for the touch down action that begins a touch gesture, but may not be invoked for the touch-moved and touch-up actions that follow.

Unit onUserLeaveHint()

Called as part of the activity lifecycle when an activity is about to go into the background as the result of user choice. For example, when the user presses the Home key, onUserLeaveHint will be called, but when an incoming phone call causes the in-call Activity to be automatically brought to the foreground, onUserLeaveHint will not be called on the activity being interrupted. In cases when it is invoked, this method is called right before the activity's onPause callback.

This callback and onUserInteraction are intended to help activities manage status bar notifications intelligently; specifically, for helping activities determine the proper time to cancel a notification.

Unit onVisibleBehindCanceled()

Called when a translucent activity over this activity is becoming opaque or another activity is being launched. Activities that override this method must call super.onVisibleBehindCanceled() or a SuperNotCalledException will be thrown.

When this method is called the activity has 500 msec to release any resources it may be using while visible in the background. If the activity has not returned from this method in 500 msec the system will destroy the activity and kill the process in order to recover the resources for another process. Otherwise onStop() will be called following return.
If you override this method you must call through to the superclass implementation.

Unit onWindowAttributesChanged(params: WindowManager.LayoutParams!)

Unit onWindowFocusChanged(hasFocus: Boolean)

Called when the current Window of the activity gains or loses focus. This is the best indicator of whether this activity is the entity with which the user actively interacts. The default implementation clears the key tracking state, so should always be called.

Note that this provides information about global focus state, which is managed independently of activity lifecycle. As such, while focus changes will generally have some relation to lifecycle changes (an activity that is stopped will not generally get window focus), you should not rely on any particular order between the callbacks here and those in the other lifecycle methods such as onResume.

As a general rule, however, a foreground activity will have window focus... unless it has displayed other dialogs or popups that take input focus, in which case the activity itself will not have focus when the other windows have it. Likewise, the system may display system-level windows (such as the status bar notification panel or a system alert) which will temporarily take window input focus without pausing the foreground activity.

Starting with android.os.Build.VERSION_CODES#Q there can be multiple resumed activities at the same time in multi-window mode, so resumed state does not guarantee window focus even if there are no overlays above.

If the intent is to know when an activity is the topmost active, the one the user interacted with last among all activities but not including non-activity windows like dialogs and popups, then onTopResumedActivityChanged(boolean) should be used. On platform versions prior to android.os.Build.VERSION_CODES#Q, onResume is the best indicator.

ActionMode? onWindowStartingActionMode(callback: ActionMode.Callback!)

Give the Activity a chance to control the UI for an action mode requested by the system.

Note: If you are looking for a notification callback that an action mode has been started for this activity, see onActionModeStarted(android.view.ActionMode).

ActionMode? onWindowStartingActionMode(callback: ActionMode.Callback!, type: Int)

Called when an action mode is being started for this window. Gives the callback an opportunity to handle the action mode in its own unique and beautiful way. If this method returns null the system can choose a way to present the mode or choose not to start the mode at all.

Unit openContextMenu(view: View!)

Programmatically opens the context menu for a particular view. The view should have been added via registerForContextMenu(android.view.View).

Unit openOptionsMenu()

Programmatically opens the options menu. If the options menu is already open, this method does nothing.

Unit overrideActivityTransition(overrideType: Int, enterAnim: Int, exitAnim: Int)

Customizes the animation for the activity transition with this activity. This can be called at any time while the activity still alive.

This is a more robust method of overriding the transition animation at runtime without relying on overridePendingTransition(int,int) which doesn't work for predictive back. However, the animation set from overridePendingTransition(int,int) still has higher priority when the system is looking for the next transition animation.

The animations resources set by this method will be chosen if and only if the activity is on top of the task while activity transitions are being played. For example, if we want to customize the opening transition when launching Activity B which gets started from Activity A, we should call this method inside B's onCreate with overrideType = OVERRIDE_TRANSITION_OPEN because the Activity B will on top of the task. And if we want to customize the closing transition when finishing Activity B and back to Activity A, since B is still is above A, we should call this method in Activity B with overrideType = OVERRIDE_TRANSITION_CLOSE.

If an Activity has called this method, and it also set another activity animation by Window.setWindowAnimations(int), the system will choose the animation set from this method.

Note that Window.setWindowAnimations, overridePendingTransition(int,int) and this method will be ignored if the Activity is started with ActivityOptions.makeSceneTransitionAnimation(Activity, Pair[]). Also note that this method can only be used to customize cross-activity transitions but not cross-task transitions which are fully non-customizable as of Android 11.

Unit overrideActivityTransition(overrideType: Int, enterAnim: Int, exitAnim: Int, backgroundColor: Int)

Customizes the animation for the activity transition with this activity. This can be called at any time while the activity still alive.

This is a more robust method of overriding the transition animation at runtime without relying on overridePendingTransition(int,int) which doesn't work for predictive back. However, the animation set from overridePendingTransition(int,int) still has higher priority when the system is looking for the next transition animation.

The animations resources set by this method will be chosen if and only if the activity is on top of the task while activity transitions are being played. For example, if we want to customize the opening transition when launching Activity B which gets started from Activity A, we should call this method inside B's onCreate with overrideType = OVERRIDE_TRANSITION_OPEN because the Activity B will on top of the task. And if we want to customize the closing transition when finishing Activity B and back to Activity A, since B is still is above A, we should call this method in Activity B with overrideType = OVERRIDE_TRANSITION_CLOSE.

If an Activity has called this method, and it also set another activity animation by Window.setWindowAnimations(int), the system will choose the animation set from this method.

Note that Window.setWindowAnimations, overridePendingTransition(int,int) and this method will be ignored if the Activity is started with ActivityOptions.makeSceneTransitionAnimation(Activity, Pair[]). Also note that this method can only be used to customize cross-activity transitions but not cross-task transitions which are fully non-customizable as of Android 11.

Unit overridePendingTransition(enterAnim: Int, exitAnim: Int)

Call immediately after one of the flavors of #startActivity(android.content.Intent) or finish to specify an explicit transition animation to perform next.

As of android.os.Build.VERSION_CODES#JELLY_BEAN an alternative to using this with starting activities is to supply the desired animation information through a ActivityOptions bundle to #startActivity(android.content.Intent,android.os.Bundle) or a related function. This allows you to specify a custom animation even when starting an activity from outside the context of the current top activity.

Af of android.os.Build.VERSION_CODES#S application can only specify a transition animation when the transition happens within the same task. System default animation is used for cross-task transition animations.

Unit overridePendingTransition(enterAnim: Int, exitAnim: Int, backgroundColor: Int)

Call immediately after one of the flavors of #startActivity(android.content.Intent) or finish to specify an explicit transition animation to perform next.

As of android.os.Build.VERSION_CODES#JELLY_BEAN an alternative to using this with starting activities is to supply the desired animation information through a ActivityOptions bundle to #startActivity(android.content.Intent,android.os.Bundle) or a related function. This allows you to specify a custom animation even when starting an activity from outside the context of the current top activity.

Unit postponeEnterTransition()

Postpone the entering activity transition when Activity was started with android.app.ActivityOptions#makeSceneTransitionAnimation(Activity, * android.util.Pair[]).

This method gives the Activity the ability to delay starting the entering and shared element transitions until all data is loaded. Until then, the Activity won't draw into its window, leaving the window transparent. This may also cause the returning animation to be delayed until data is ready. This method should be called in onCreate(android.os.Bundle) or in onActivityReenter(int,android.content.Intent). startPostponedEnterTransition() must be called to allow the Activity to start the transitions. If the Activity did not use android.app.ActivityOptions#makeSceneTransitionAnimation(Activity, * android.util.Pair[]), then this method does nothing.

Unit recreate()

Cause this Activity to be recreated with a new instance. This results in essentially the same flow as when the Activity is created due to a configuration change -- the current instance will go through its lifecycle to onDestroy and a new instance then created after it.

Unit registerActivityLifecycleCallbacks(callback: Application.ActivityLifecycleCallbacks)

Register an Application.ActivityLifecycleCallbacks instance that receives lifecycle callbacks for only this Activity.

In relation to any Application registered callbacks, the callbacks registered here will always occur nested within those callbacks. This means:

If multiple callbacks are registered here, they receive events in a first in (up through Application.ActivityLifecycleCallbacks.onActivityPostResumed, last out ordering.

It is strongly recommended to register this in the constructor of your Activity to ensure you get all available callbacks. As this callback is associated with only this Activity, it is not usually necessary to unregister it unless you specifically do not want to receive further lifecycle callbacks.

Unit registerComponentCallbacks(callback: ComponentCallbacks!)

Unit registerForContextMenu(view: View!)

Registers a context menu to be shown for the given view (multiple views can show the context menu). This method will set the OnCreateContextMenuListener on the view to this activity, so onCreateContextMenu(android.view.ContextMenu,android.view.View,android.view.ContextMenu.ContextMenuInfo) will be called when it is time to show the context menu.

Unit registerScreenCaptureCallback(executor: Executor, callback: Activity.ScreenCaptureCallback)

Registers a screen capture callback for this activity. The callback will be triggered when a screen capture of this activity is attempted. This callback will be executed on the thread of the passed executor. For details, see ScreenCaptureCallback.onScreenCaptured.
Requires android.Manifest.permission#DETECT_SCREEN_CAPTURE

Boolean releaseInstance()

Ask that the local app instance of this activity be released to free up its memory. This is asking for the activity to be destroyed, but does not finish the activity -- a new instance of the activity will later be re-created if needed due to the user navigating back to it.

Unit removeDialog(id: Int)

Removes any internal references to a dialog managed by this Activity. If the dialog is showing, it will dismiss it as part of the clean up.

This can be useful if you know that you will never show a dialog again and want to avoid the overhead of saving and restoring it in the future.

As of android.os.Build.VERSION_CODES#GINGERBREAD, this function will not throw an exception if you try to remove an ID that does not currently have an associated dialog.

Unit reportFullyDrawn()

Report to the system that your app is now fully drawn, for diagnostic and optimization purposes. The system may adjust optimizations to prioritize work that happens before reportFullyDrawn is called, to improve app startup. Misrepresenting the startup window by calling reportFullyDrawn too late or too early may decrease application and startup performance.

This is also used to help instrument application launch times, so that the app can report when it is fully in a usable state; without this, the only thing the system itself can determine is the point at which the activity's window is first drawn and displayed. To participate in app launch time measurement, you should always call this method after first launch (when onCreate(android.os.Bundle) is called), at the point where you have entirely drawn your UI and populated with all of the significant data. You can safely call this method any time after first launch as well, in which case it will simply be ignored.

If this method is called before the activity's window is first drawn and displayed as measured by the system, the reported time here will be shifted to the system measured time.

DragAndDropPermissions! requestDragAndDropPermissions(event: DragEvent!)

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

Unit requestFullscreenMode(request: Int, approvalCallback: OutcomeReceiver<Void!, Throwable!>?)

Request to put the activity into fullscreen. The requester must be pinned or the top-most activity of the focused display which can be verified using onTopResumedActivityChanged(boolean). The request should also be a response to a user input. When getting fullscreen and receiving corresponding onConfigurationChanged(android.content.res.Configuration) and onMultiWindowModeChanged(boolean,android.content.res.Configuration), the activity should relayout itself and the system bars' visibilities can be controlled as usual fullscreen apps. Calling it again with the exit request can restore the activity to the previous status. This will only happen when it got into fullscreen through this API.

Unit requestPermissions(permissions: Array<String!>, requestCode: Int)

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

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

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

If your app does not have the requested permissions the user will be presented with UI for accepting them. After the user has accepted or rejected the requested permissions you will receive a callback on #onRequestPermissionsResult reporting whether the permissions were granted or not.

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

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

When checking whether you have a permission you should use checkSelfPermission(java.lang.String).

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

The permissions samples repo demonstrates how to use this method to request permissions at run time.

Unit requestPermissions(permissions: Array<String!>, requestCode: Int, deviceId: Int)

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

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

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

If your app does not have the requested permissions the user will be presented with UI for accepting them. After the user has accepted or rejected the requested permissions you will receive a callback on #onRequestPermissionsResult reporting whether the permissions were granted or not.

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

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

When checking whether you have a permission you should use checkSelfPermission(java.lang.String).

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

The permissions samples repo demonstrates how to use this method to request permissions at run time.

Unit requestShowKeyboardShortcuts()

Request the Keyboard Shortcuts screen to show up. This will trigger onProvideKeyboardShortcuts to retrieve the shortcuts for the foreground activity.

Boolean requestVisibleBehind(visible: Boolean)

Activities that want to remain visible behind a translucent activity above them must call this method anytime between the start of onResume() and the return from onPause(). If this call is successful then the activity will remain visible after onPause() is called, and is allowed to continue playing media in the background.

The actions of this call are reset each time that this activity is brought to the front. That is, every time onResume() is called the activity will be assumed to not have requested visible behind. Therefore, if you want this activity to continue to be visible in the background you must call this method again.

Only fullscreen opaque activities may make this call. I.e. this call is a nop for dialog and translucent activities.

Under all circumstances, the activity must stop playing and release resources prior to or within a call to onVisibleBehindCanceled() or if this call returns false.

False will be returned any time this method is called between the return of onPause and the next call to onResume.

Boolean requestWindowFeature(featureId: Int)

Enable extended window features. This is a convenience for calling getWindow().requestFeature().

T requireViewById(id: Int)

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

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

Unit runOnUiThread(action: Runnable!)

Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.

Unit setActionBar(toolbar: Toolbar?)

Set a Toolbar to act as the ActionBar for this Activity window.

When set to a non-null value the getActionBar() method will return an ActionBar object that can be used to control the given toolbar as if it were a traditional window decor action bar. The toolbar's menu will be populated with the Activity's options menu and the navigation button will be wired through the standard home menu select action.

In order to use a Toolbar within the Activity's window content the application must not request the window feature FEATURE_ACTION_BAR.

Unit setAllowCrossUidActivitySwitchFromBelow(allowed: Boolean)

Specifies whether the activities below this one in the task can also start other activities or finish the task.

Starting from Target SDK Level android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM, apps may be blocked from starting new activities or finishing their task unless the top activity of such task belong to the same UID for security reasons.

Setting this flag to true will allow the launching app to ignore the restriction if this activity is on top. Apps matching the UID of this activity are always exempt.

Unit setContentTransitionManager(tm: TransitionManager!)

Set the TransitionManager to use for default transitions in this window. Requires Window.FEATURE_CONTENT_TRANSITIONS.

Unit setContentView(view: View!)

Set the activity content to an explicit view. This view is placed directly into the activity's view hierarchy. It can itself be a complex view hierarchy. When calling this method, the layout parameters of the specified view are ignored. Both the width and the height of the view are set by default to ViewGroup.LayoutParams.MATCH_PARENT. To use your own layout parameters, invoke setContentView(android.view.View,android.view.ViewGroup.LayoutParams) instead.

Unit setContentView(view: View!, params: ViewGroup.LayoutParams!)

Set the activity content to an explicit view. This view is placed directly into the activity's view hierarchy. It can itself be a complex view hierarchy.

Unit setContentView(layoutResID: Int)

Set the activity content from a layout resource. The resource will be inflated, adding all top-level views to the activity.

Unit setDefaultKeyMode(mode: Int)

Select the default key handling for this activity. This controls what will happen to key events that are not otherwise handled. The default mode (DEFAULT_KEYS_DISABLE) will simply drop them on the floor. Other modes allow you to launch the dialer (DEFAULT_KEYS_DIALER), execute a shortcut in your options menu without requiring the menu key be held down (DEFAULT_KEYS_SHORTCUT), or launch a search (DEFAULT_KEYS_SEARCH_LOCAL and DEFAULT_KEYS_SEARCH_GLOBAL).

Note that the mode selected here does not impact the default handling of system keys, such as the "back" and "menu" keys, and your activity and its views always get a first chance to receive and handle all application keys.

Unit setEnterSharedElementCallback(callback: SharedElementCallback!)

When android.app.ActivityOptions#makeSceneTransitionAnimation(Activity, * android.view.View, String) was used to start an Activity, callback will be called to handle shared elements on the launched Activity. This requires Window.FEATURE_ACTIVITY_TRANSITIONS.

Unit setExitSharedElementCallback(callback: SharedElementCallback!)

When android.app.ActivityOptions#makeSceneTransitionAnimation(Activity, * android.view.View, String) was used to start an Activity, callback will be called to handle shared elements on the launching Activity. Most calls will only come when returning from the started Activity. This requires Window.FEATURE_ACTIVITY_TRANSITIONS.

Unit setFeatureDrawable(featureId: Int, drawable: Drawable!)

Convenience for calling android.view.Window#setFeatureDrawable(int, Drawable).

Unit setFeatureDrawableAlpha(featureId: Int, alpha: Int)

Convenience for calling android.view.Window#setFeatureDrawableAlpha.

Unit setFeatureDrawableResource(featureId: Int, resId: Int)

Convenience for calling android.view.Window#setFeatureDrawableResource.

Unit setFeatureDrawableUri(featureId: Int, uri: Uri!)

Convenience for calling android.view.Window#setFeatureDrawableUri.

Unit setFinishOnTouchOutside(finish: Boolean)

Sets whether this activity is finished when touched outside its window's bounds.

Unit setImmersive(i: Boolean)

Adjust the current immersive mode setting. Note that changing this value will have no effect on the activity's android.content.pm.ActivityInfo structure; that is, if android:immersive is set to true in the application's manifest entry for this activity, the ActivityInfo.flags member will always have its FLAG_IMMERSIVE bit set.

Unit setInheritShowWhenLocked(inheritShowWhenLocked: Boolean)

Specifies whether this Activity should be shown on top of the lock screen whenever the lockscreen is up and this activity has another activity behind it with the showWhenLock attribute set. That is, this activity is only visible on the lock screen if there is another activity with the showWhenLock attribute visible at the same time on the lock screen. A use case for this is permission dialogs, that should only be visible on the lock screen if their requesting activity is also visible. This value can be set as a manifest attribute using android.R.attr#inheritShowWhenLocked.

Unit setIntent(newIntent: Intent!)

Changes the intent returned by getIntent. This holds a reference to the given intent; it does not copy it. Often used in conjunction with onNewIntent(android.content.Intent).

Unit setIntent(newIntent: Intent?, newCaller: ComponentCaller?)

Changes the intent returned by getIntent, and ComponentCaller returned by getCaller. This holds references to the given intent, and ComponentCaller; it does not copy them. Often used in conjunction with onNewIntent(android.content.Intent). To retrieve the caller from onNewIntent(android.content.Intent), use getCurrentCaller, otherwise override onNewIntent(android.content.Intent,android.app.ComponentCaller).

Unit setLocusContext(locusId: LocusId?, bundle: Bundle?)

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

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

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

Unit setMediaController(controller: MediaController!)

Sets a MediaController to send media keys and volume changes to.

The controller will be tied to the window of this Activity. Media key and volume events which are received while the Activity is in the foreground will be forwarded to the controller and used to invoke transport controls or adjust the volume. This may be used instead of or in addition to setVolumeControlStream to affect a specific session instead of a specific stream.

It is not guaranteed that the hardware volume controls will always change this session's volume (for example, if a call is in progress, its stream's volume may be changed instead). To reset back to the default use null as the controller.

Unit setPictureInPictureParams(params: PictureInPictureParams)

Updates the properties of the picture-in-picture activity, or sets it to be used later when enterPictureInPictureMode() is called.

Unit setProgress(progress: Int)

Sets the progress for the progress bars in the title.

In order for the progress bar to be shown, the feature must be requested via requestWindowFeature(int).

Unit setProgressBarIndeterminate(indeterminate: Boolean)

Sets whether the horizontal progress bar in the title should be indeterminate (the circular is always indeterminate).

In order for the progress bar to be shown, the feature must be requested via requestWindowFeature(int).

Unit setProgressBarIndeterminateVisibility(visible: Boolean)

Sets the visibility of the indeterminate progress bar in the title.

In order for the progress bar to be shown, the feature must be requested via requestWindowFeature(int).

Unit setProgressBarVisibility(visible: Boolean)

Sets the visibility of the progress bar in the title.

In order for the progress bar to be shown, the feature must be requested via requestWindowFeature(int).

Unit setRecentsScreenshotEnabled(enabled: Boolean)

If set to false, this indicates to the system that it should never take a screenshot of the activity to be used as a representation in recents screen. By default, this value is true.

Note that the system may use the window background of the theme instead to represent the window when it is not running.

Also note that in comparison to android.view.WindowManager.LayoutParams#FLAG_SECURE, this only affects the behavior when the activity's screenshot would be used as a representation when the activity is not in a started state, i.e. in Overview. The system may still take screenshots of the activity in other contexts; for example, when the user takes a screenshot of the entire screen, or when the active android.service.voice.VoiceInteractionService requests a screenshot via android.service.voice.VoiceInteractionSession#SHOW_WITH_SCREENSHOT.

Unit setRequestedOrientation(requestedOrientation: Int)

Change the desired orientation of this activity. If the activity is currently in the foreground or otherwise impacting the screen orientation, the screen will immediately be changed (possibly causing the activity to be restarted). Otherwise, this will be used the next time the activity is visible. Note: Device manufacturers can configure devices to override (ignore) calls to this method to improve the layout of orientation-restricted apps. See Device compatibility mode.

Unit setResult(resultCode: Int)

Call this to set the result that your activity will return to its caller.

Unit setResult(resultCode: Int, data: Intent!)

Call this to set the result that your activity will return to its caller.

As of android.os.Build.VERSION_CODES#GINGERBREAD, the Intent you supply here can have Intent.FLAG_GRANT_READ_URI_PERMISSION and/or Intent.FLAG_GRANT_WRITE_URI_PERMISSION set. This will grant the Activity receiving the result access to the specific URIs in the Intent. Access will remain until the Activity has finished (it will remain across the hosting process being killed and other temporary destruction) and will be added to any existing set of URI permissions it already holds.

Unit setSecondaryProgress(secondaryProgress: Int)

Sets the secondary progress for the progress bar in the title. This progress is drawn between the primary progress (set via setProgress(int) and the background. It can be ideal for media scenarios such as showing the buffering progress while the default progress shows the play progress.

In order for the progress bar to be shown, the feature must be requested via requestWindowFeature(int).

Unit setShouldDockBigOverlays(shouldDockBigOverlays: Boolean)

Specifies a preference to dock big overlays like the expanded picture-in-picture on TV (see PictureInPictureParams.Builder.setExpandedAspectRatio). Docking puts the big overlay side-by-side next to this activity, so that both windows are fully visible to the user.

If unspecified, whether the overlay window will be docked or not, will be defined by the system.

If specified, the system will try to respect the preference, but it may be overridden by a user preference.

Unit setShowWhenLocked(showWhenLocked: Boolean)

Specifies whether an Activity should be shown on top of the lock screen whenever the lockscreen is up and the activity is resumed. Normally an activity will be transitioned to the stopped state if it is started while the lockscreen is up, but with this flag set the activity will remain in the resumed state visible on-top of the lock screen. This value can be set as a manifest attribute using android.R.attr#showWhenLocked.

Unit setTaskDescription(taskDescription: ActivityManager.TaskDescription!)

Sets information describing the task with this activity for presentation inside the Recents System UI. When ActivityManager.getRecentTasks is called, the activities of each task are traversed in order from the topmost activity to the bottommost. The traversal continues for each property until a suitable value is found. For each task the taskDescription will be returned in android.app.ActivityManager.TaskDescription.

Unit setTheme(resid: Int)

Unit setTitle(titleId: Int)

Change the title associated with this activity. If this is a top-level activity, the title for its window will change. If it is an embedded activity, the parent can do whatever it wants with it.

Unit setTitle(title: CharSequence!)

Change the title associated with this activity. If this is a top-level activity, the title for its window will change. If it is an embedded activity, the parent can do whatever it wants with it.

Unit setTitleColor(textColor: Int)

Change the color of the title associated with this activity.

This method is deprecated starting in API Level 11 and replaced by action bar styles. For information on styling the Action Bar, read the Action Bar developer guide.

Boolean setTranslucent(translucent: Boolean)

Convert an activity, which particularly with android.R.attr#windowIsTranslucent or android.R.attr#windowIsFloating attribute, to a fullscreen opaque activity, or convert it from opaque back to translucent.

Unit setTurnScreenOn(turnScreenOn: Boolean)

Specifies whether the screen should be turned on when the Activity is resumed. Normally an activity will be transitioned to the stopped state if it is started while the screen if off, but with this flag set the activity will cause the screen to turn on if the activity will be visible and resumed due to the screen coming on. The screen will not be turned on if the activity won't be visible after the screen is turned on. This flag is normally used in conjunction with the android.R.attr#showWhenLocked flag to make sure the activity is visible after the screen is turned on when the lockscreen is up. In addition, if this flag is set and the activity calls android.app.KeyguardManager#requestDismissKeyguard(android.app.Activity,android.app.KeyguardManager.KeyguardDismissCallback) the screen will turn on.

Unit setVisible(visible: Boolean)

Control whether this activity's main window is visible. This is intended only for the special case of an activity that is not going to show a UI itself, but can't just finish prior to onResume() because it needs to wait for a service binding or such. Setting this to false allows you to prevent your UI from being shown during that time.

The default value for this is taken from the android.R.attr#windowNoDisplay attribute of the activity's theme.

Unit setVolumeControlStream(streamType: Int)

Suggests an audio stream whose volume should be changed by the hardware volume controls.

The suggested audio stream will be tied to the window of this Activity. Volume requests which are received while the Activity is in the foreground will affect this stream.

It is not guaranteed that the hardware volume controls will always change this stream's volume (for example, if a call is in progress, its stream's volume may be changed instead). To reset back to the default, use AudioManager.USE_DEFAULT_STREAM_TYPE.

Unit setVrModeEnabled(enabled: Boolean, requestedComponent: ComponentName)

Enable or disable virtual reality (VR) mode for this Activity.

VR mode is a hint to Android system to switch to a mode optimized for VR applications while this Activity has user focus.

It is recommended that applications additionally declare android.R.attr#enableVrMode in their manifest to allow for smooth activity transitions when switching between VR activities.

If the requested android.service.vr.VrListenerService component is not available, VR mode will not be started. Developers can handle this case as follows:

String servicePackage = "com.whatever.app";
  String serviceClass = "com.whatever.app.MyVrListenerService";
 
  // Name of the component of the VrListenerService to start.
  ComponentName serviceComponent = new ComponentName(servicePackage, serviceClass);
 
  try {
     setVrModeEnabled(true, myComponentName);
  } catch (PackageManager.NameNotFoundException e) {
         List<ApplicationInfo> installed = getPackageManager().getInstalledApplications(0);
         boolean isInstalled = false;
         for (ApplicationInfo app : installed) {
             if (app.packageName.equals(servicePackage)) {
                 isInstalled = true;
                 break;
             }
         }
         if (isInstalled) {
             // Package is installed, but not enabled in Settings.  Let user enable it.
             startActivity(new Intent(Settings.ACTION_VR_LISTENER_SETTINGS));
         } else {
             // Package is not installed.  Send an intent to download this.
             sentIntentToLaunchAppStore(servicePackage);
         }
  }
  

Boolean shouldDockBigOverlays()

Returns whether big overlays should be docked next to the activity as set by setShouldDockBigOverlays.

Boolean shouldShowRequestPermissionRationale(permission: String)

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

Boolean shouldShowRequestPermissionRationale(permission: String, deviceId: Int)

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

Boolean shouldUpRecreateTask(targetIntent: Intent!)

Returns true if the app should recreate the task when navigating 'up' from this activity by using targetIntent.

If this method returns false the app can trivially call navigateUpTo(android.content.Intent) using the same parameters to correctly perform up navigation. If this method returns false, the app should synthesize a new task stack by using TaskStackBuilder or another similar mechanism to perform up navigation.

Boolean showAssist(args: Bundle!)

Ask to have the current assistant shown to the user. This only works if the calling activity is the current foreground activity. It is the same as calling VoiceInteractionService.showSession and requesting all of the possible context. The receiver will always see android.service.voice.VoiceInteractionSession#SHOW_SOURCE_APPLICATION set.

Unit showDialog(id: Int)

Simple version of showDialog(int,android.os.Bundle) that does not take any arguments. Simply calls showDialog(int,android.os.Bundle) with null arguments.

Boolean showDialog(id: Int, args: Bundle!)

Show a dialog managed by this activity. A call to onCreateDialog(int,android.os.Bundle) will be made with the same id the first time this is called for a given id. From thereafter, the dialog will be automatically saved and restored. If you are targeting android.os.Build.VERSION_CODES#HONEYCOMB or later, consider instead using a DialogFragment instead.

Each time a dialog is shown, onPrepareDialog(int,android.app.Dialog,android.os.Bundle) will be made to provide an opportunity to do any timely preparation.

Unit showLockTaskEscapeMessage()

Shows the user the system defined message for telling the user how to exit lock task mode. The task containing this activity must be in lock task mode at the time of this call for the message to be displayed.

ActionMode? startActionMode(callback: ActionMode.Callback!)

Start an action mode of the default type ActionMode.TYPE_PRIMARY.

ActionMode? startActionMode(callback: ActionMode.Callback!, type: Int)

Start an action mode of the given type.

Unit startActivities(intents: Array<Intent!>!)

Same as #startActivities(android.content.Intent[],android.os.Bundle) with no options specified.

Unit startActivities(intents: Array<Intent!>!, options: Bundle?)

Launch a new activity. You will not receive any information about when the activity exits. This implementation overrides the base version, providing information about the activity performing the launch. Because of this additional information, the Intent.FLAG_ACTIVITY_NEW_TASK launch flag is not required; if not specified, the new activity will be added to the task of the caller.

This method throws android.content.ActivityNotFoundException if there was no Activity found to run the given Intent.

Unit startActivity(intent: Intent!)

Same as #startActivity(android.content.Intent,android.os.Bundle) with no options specified.

Unit startActivity(intent: Intent!, options: Bundle?)

Launch a new activity. You will not receive any information about when the activity exits. This implementation overrides the base version, providing information about the activity performing the launch. Because of this additional information, the Intent.FLAG_ACTIVITY_NEW_TASK launch flag is not required; if not specified, the new activity will be added to the task of the caller.

This method throws android.content.ActivityNotFoundException if there was no Activity found to run the given Intent.

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

Same as calling startActivityForResult(android.content.Intent,int,android.os.Bundle) with no options.

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

Launch an activity for which you would like a result when it finished. When this activity exits, your onActivityResult() method will be called with the given requestCode. Using a negative requestCode is the same as calling #startActivity (the activity is not launched as a sub-activity).

Note that this method should only be used with Intent protocols that are defined to return a result. In other protocols (such as Intent.ACTION_MAIN or Intent.ACTION_VIEW), you may not get the result when you expect. For example, if the activity you are launching uses Intent.FLAG_ACTIVITY_NEW_TASK, it will not run in your task and thus you will immediately receive a cancel result.

As a special case, if you call startActivityForResult() with a requestCode >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your activity, then your window will not be displayed until a result is returned back from the started activity. This is to avoid visible flickering when redirecting to another activity.

This method throws android.content.ActivityNotFoundException if there was no Activity found to run the given Intent.

Unit startActivityFromChild(child: Activity, intent: Intent!, requestCode: Int)

Same as calling startActivityFromChild(android.app.Activity,android.content.Intent,int,android.os.Bundle) with no options.

Unit startActivityFromChild(child: Activity, intent: Intent!, requestCode: Int, options: Bundle?)

This is called when a child activity of this one calls its #startActivity or #startActivityForResult method.

This method throws android.content.ActivityNotFoundException if there was no Activity found to run the given Intent.

Unit startActivityFromFragment(fragment: Fragment, intent: Intent!, requestCode: Int)

Same as calling startActivityFromFragment(android.app.Fragment,android.content.Intent,int,android.os.Bundle) with no options.

Unit startActivityFromFragment(fragment: Fragment, intent: Intent!, requestCode: Int, options: Bundle?)

This is called when a Fragment in this activity calls its android.app.Fragment#startActivity or android.app.Fragment#startActivityForResult method.

This method throws android.content.ActivityNotFoundException if there was no Activity found to run the given Intent.

Boolean startActivityIfNeeded(intent: Intent, requestCode: Int)

Same as calling startActivityIfNeeded(android.content.Intent,int,android.os.Bundle) with no options.

Boolean startActivityIfNeeded(intent: Intent, requestCode: Int, options: Bundle?)

A special variation to launch an activity only if a new activity instance is needed to handle the given Intent. In other words, this is just like startActivityForResult(android.content.Intent,int) except: if you are using the Intent.FLAG_ACTIVITY_SINGLE_TOP flag, or singleTask or singleTop launchMode, and the activity that handles intent is the same as your currently running activity, then a new instance is not needed. In this case, instead of the normal behavior of calling #onNewIntent this function will return and you can handle the Intent yourself.

This function can only be called from a top-level activity; if it is called from a child activity, a runtime exception will be thrown.

Unit startIntentSender(intent: IntentSender!, fillInIntent: Intent?, flagsMask: Int, flagsValues: Int, extraFlags: Int)

Same as calling #startIntentSender(android.content.IntentSender,android.content.Intent,int,int,int,android.os.Bundle) with no options.

Unit startIntentSender(intent: IntentSender!, fillInIntent: Intent?, flagsMask: Int, flagsValues: Int, extraFlags: Int, options: Bundle?)

Like #startActivity(android.content.Intent,android.os.Bundle), but taking a IntentSender to start; see startIntentSenderForResult(android.content.IntentSender,int,android.content.Intent,int,int,int,android.os.Bundle) for more information.

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

Same as calling startIntentSenderForResult(android.content.IntentSender,int,android.content.Intent,int,int,int,android.os.Bundle) with no options.

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

Like startActivityForResult(android.content.Intent,int), but allowing you to use a IntentSender to describe the activity to be started. If the IntentSender is for an activity, that activity will be started as if you had called the regular startActivityForResult(android.content.Intent,int) here; otherwise, its associated action will be executed (such as sending a broadcast) as if you had called android.content.IntentSender#sendIntent on it.

Unit startIntentSenderFromChild(child: Activity!, intent: IntentSender!, requestCode: Int, fillInIntent: Intent!, flagsMask: Int, flagsValues: Int, extraFlags: Int)

Same as calling startIntentSenderFromChild(android.app.Activity,android.content.IntentSender,int,android.content.Intent,int,int,int,android.os.Bundle) with no options.

Unit startIntentSenderFromChild(child: Activity!, intent: IntentSender!, requestCode: Int, fillInIntent: Intent!, flagsMask: Int, flagsValues: Int, extraFlags: Int, options: Bundle?)

Like startActivityFromChild(android.app.Activity,android.content.Intent,int), but taking a IntentSender; see startIntentSenderForResult(android.content.IntentSender,int,android.content.Intent,int,int,int) for more information.

Unit startLocalVoiceInteraction(privateOptions: Bundle!)

Starts a local voice interaction session. When ready, onLocalVoiceInteractionStarted() is called. You can pass a bundle of private options to the registered voice interaction service.

Unit startLockTask()

Request to put this activity in a mode where the user is locked to a restricted set of applications.

If DevicePolicyManager.isLockTaskPermitted(String) returns true for this component, the current task will be launched directly into LockTask mode. Only apps allowlisted by DevicePolicyManager.setLockTaskPackages(ComponentName, String[]) can be launched while LockTask mode is active. The user will not be able to leave this mode until this activity calls stopLockTask(). Calling this method while the device is already in LockTask mode has no effect.

Otherwise, the current task will be launched into screen pinning mode. In this case, the system will prompt the user with a dialog requesting permission to use this mode. The user can exit at any time through instructions shown on the request dialog. Calling stopLockTask() will also terminate this mode.

Note: this method can only be called when the activity is foreground. That is, between onResume() and onPause().

Unit startManagingCursor(c: Cursor!)

This method allows the activity to take care of managing the given Cursor's lifecycle for you based on the activity's lifecycle. That is, when the activity is stopped it will automatically call Cursor.deactivate on the given Cursor, and when it is later restarted it will call Cursor.requery for you. When the activity is destroyed, all managed Cursors will be closed automatically. If you are targeting android.os.Build.VERSION_CODES#HONEYCOMB or later, consider instead using LoaderManager instead, available via getLoaderManager().

Warning: Do not call android.database.Cursor#close() on cursor obtained from managedQuery, because the activity will do that for you at the appropriate time. However, if you call stopManagingCursor on a cursor from a managed query, the system will not automatically close the cursor and, in that case, you must call android.database.Cursor#close().

Boolean startNextMatchingActivity(intent: Intent)

Same as calling startNextMatchingActivity(android.content.Intent,android.os.Bundle) with no options.

Boolean startNextMatchingActivity(intent: Intent, options: Bundle?)

Special version of starting an activity, for use when you are replacing other activity components. You can use this to hand the Intent off to the next Activity that can handle it. You typically call this in #onCreate with the Intent returned by getIntent.

Unit startPostponedEnterTransition()

Begin postponed transitions after postponeEnterTransition() was called. If postponeEnterTransition() was called, you must call startPostponedEnterTransition() to have your Activity start drawing.

Unit startSearch(initialQuery: String?, selectInitialQuery: Boolean, appSearchData: Bundle?, globalSearch: Boolean)

This hook is called to launch the search UI.

It is typically called from onSearchRequested(), either directly from Activity.onSearchRequested() or from an overridden version in any given Activity. If your goal is simply to activate search, it is preferred to call onSearchRequested(), which may have been overridden elsewhere in your Activity. If your goal is to inject specific data such as context data, it is preferred to override onSearchRequested(), so that any callers to it will benefit from the override.

Note: when running in a Configuration.UI_MODE_TYPE_WATCH, use of this API is not supported.

Unit stopLocalVoiceInteraction()

Request to terminate the current voice interaction that was previously started using startLocalVoiceInteraction(android.os.Bundle). When the interaction is terminated, onLocalVoiceInteractionStopped() will be called.

Unit stopLockTask()

Stop the current task from being locked.

Called to end the LockTask or screen pinning mode started by startLockTask(). This can only be called by activities that have called startLockTask() previously.

Note: If the device is in LockTask mode that is not initially started by this activity, then calling this method will not terminate the LockTask mode, but only finish its own task. The device will remain in LockTask mode, until the activity which started the LockTask mode calls this method, or until its allowlist authorization is revoked by DevicePolicyManager.setLockTaskPackages(ComponentName, String[]).

Unit stopManagingCursor(c: Cursor!)

Given a Cursor that was previously given to startManagingCursor, stop the activity's management of that cursor.

Warning: After calling this method on a cursor from a managed query, the system will not automatically close the cursor and you must call android.database.Cursor#close().

Unit takeKeyEvents(get: Boolean)

Request that key events come to this activity. Use this if your activity has no views with focus, but the activity still wants a chance to process key events.

Unit triggerSearch(query: String!, appSearchData: Bundle?)

Similar to startSearch, but actually fires off the search query after invoking the search dialog. Made available for testing purposes.

Unit unregisterActivityLifecycleCallbacks(callback: Application.ActivityLifecycleCallbacks)

Unregister an Application.ActivityLifecycleCallbacks previously registered with registerActivityLifecycleCallbacks. It will not receive any further callbacks.

Unit unregisterComponentCallbacks(callback: ComponentCallbacks!)

Unit unregisterForContextMenu(view: View!)

Prevents a context menu to be shown for the given view. This method will remove the OnCreateContextMenuListener on the view.

Unit unregisterScreenCaptureCallback(callback: Activity.ScreenCaptureCallback)

Unregisters a screen capture callback for this surface.
Requires android.Manifest.permission#DETECT_SCREEN_CAPTURE

Unit applyOverrideConfiguration(overrideConfiguration: Configuration!)

Call to set an "override configuration" on this context -- this is a configuration that replies one or more values of the standard configuration that is applied to the context. See Context.createConfigurationContext(Configuration) for more information.

This method can only be called once, and must be called before any calls to #getResources() or #getAssets() are made.

AssetManager! getAssets()

Resources! getResources()

Resources.Theme! getTheme()

Unit setTheme(theme: Resources.Theme?)

Set the configure the current theme. If null is provided then the default Theme is returned on the next call to #getTheme()

Boolean bindIsolatedService(service: Intent, flags: Int, instanceName: String, executor: Executor, conn: ServiceConnection)

Boolean bindService(service: Intent, flags: Context.BindServiceFlags, executor: Executor, conn: ServiceConnection)

See bindService(android.content.Intent,int,java.util.concurrent.Executor,android.content.ServiceConnection) Call BindServiceFlags.of(long) to obtain a BindServiceFlags object.

Boolean bindService(service: Intent, conn: ServiceConnection, flags: Context.BindServiceFlags)

See bindService(android.content.Intent,android.content.ServiceConnection,int) Call BindServiceFlags.of(long) to obtain a BindServiceFlags object.

Boolean bindService(service: Intent, conn: ServiceConnection, flags: Int)

Boolean bindService(service: Intent, flags: Int, executor: Executor, conn: ServiceConnection)

Int checkCallingOrSelfPermission(permission: String)

Int checkCallingOrSelfUriPermission(uri: Uri!, modeFlags: Int)

IntArray checkCallingOrSelfUriPermissions(uris: MutableList<Uri!>, modeFlags: Int)

Determine whether the calling process of an IPC or you has been granted permission to access a list of URIs. This is the same as checkCallingUriPermission, except it grants your own permissions if you are not currently processing an IPC. Use with care!

Int checkCallingPermission(permission: String)

Int checkCallingUriPermission(uri: Uri!, modeFlags: Int)

IntArray checkCallingUriPermissions(uris: MutableList<Uri!>, modeFlags: Int)

Determine whether the calling process and uid has been granted permission to access a list of URIs. This is basically the same as calling checkUriPermissions(java.util.List,int,int,int) with the pid and uid returned by android.os.Binder#getCallingPid and android.os.Binder#getCallingUid. One important difference is that if you are not currently processing an IPC, this function will always fail.

Int checkContentUriPermissionFull(uri: Uri, pid: Int, uid: Int, modeFlags: Int)

Determine whether a particular process and uid has been granted permission to access a specific content URI.

Unlike checkUriPermission(android.net.Uri,int,int,int), this method checks for general access to the URI's content provider, as well as explicitly granted permissions.

Note, this check will throw an IllegalArgumentException for non-content URIs.

Int checkPermission(permission: String, pid: Int, uid: Int)

Int checkSelfPermission(permission: String)

Int checkUriPermission(uri: Uri!, pid: Int, uid: Int, modeFlags: Int)

Int checkUriPermission(uri: Uri?, readPermission: String?, writePermission: String?, pid: Int, uid: Int, modeFlags: Int)

Check both a Uri and normal permission. This allows you to perform both checkPermission and #checkUriPermission in one call.

IntArray checkUriPermissions(uris: MutableList<Uri!>, pid: Int, uid: Int, modeFlags: Int)

Determine whether a particular process and uid has been granted permission to access a list of URIs. This only checks for permissions that have been explicitly granted -- if the given process/uid has more general access to the URI's content provider then this check will always fail. Note: On SDK Version android.os.Build.VERSION_CODES#S, calling this method from a secondary-user's context will incorrectly return PackageManager.PERMISSION_DENIED for all {code uris}.

Unit clearWallpaper()

Context createAttributionContext(attributionTag: String?)

Return a new Context object for the current Context but attribute to a different tag. In complex apps attribution tagging can be used to distinguish between separate logical parts.

Context! createConfigurationContext(overrideConfiguration: Configuration)

Context createContext(contextParams: ContextParams)

Creates a context with specific properties and behaviors.

Context createDeviceContext(deviceId: Int)

Returns a new Context object from the current context but with device association given by the deviceId. Each call to this method returns a new instance of a context object. Context objects are not shared; however, common state (such as the ClassLoader and other resources for the same configuration) can be shared, so the Context itself is lightweight.

Applications that run on virtual devices may use this method to access the default device capabilities and functionality (by passing Context.DEVICE_ID_DEFAULT. Similarly, applications running on the default device may access the functionality of virtual devices.

Note that the newly created instance will be associated with the same display as the parent Context, regardless of the device ID passed here.

Context! createDeviceProtectedStorageContext()

Context! createDisplayContext(display: Display)

Context! createPackageContext(packageName: String!, flags: Int)

Context createWindowContext(display: Display, type: Int, options: Bundle?)

Creates a Context for a non-activity window on the given Display.

Similar to createWindowContext(int,android.os.Bundle), but the display is passed in, instead of implicitly using the original Context's Display.

Context createWindowContext(type: Int, options: Bundle?)

Creates a Context for a non-activity window.

A window context is a context that can be used to add non-activity windows, such as android.view.WindowManager.LayoutParams#TYPE_APPLICATION_OVERLAY. A window context must be created from a context that has an associated Display, such as Activity or a context created with createDisplayContext(android.view.Display).

The window context is created with the appropriate Configuration for the area of the display that the windows created with it can occupy; it must be used when inflating views, such that they can be inflated with proper Resources. Below is a sample code to add an application overlay window on the primary display:

...
  final DisplayManager dm = anyContext.getSystemService(DisplayManager.class);
  final Display primaryDisplay = dm.getDisplay(DEFAULT_DISPLAY);
  final Context windowContext = anyContext.createDisplayContext(primaryDisplay)
          .createWindowContext(TYPE_APPLICATION_OVERLAY, null);
  final View overlayView = Inflater.from(windowContext).inflate(someLayoutXml, null);
 
  // WindowManager.LayoutParams initialization
  ...
  // The types used in addView and createWindowContext must match.
  mParams.type = TYPE_APPLICATION_OVERLAY;
  ...
 
  windowContext.getSystemService(WindowManager.class).addView(overlayView, mParams);
  

This context's configuration and resources are adjusted to an area of the display where the windows with provided type will be added. Note that all windows associated with the same context will have an affinity and can only be moved together between different displays or areas on a display. If there is a need to add different window types, or non-associated windows, separate Contexts should be used.

Creating a window context is an expensive operation. Misuse of this API may lead to a huge performance drop. The best practice is to use the same window context when possible. An approach is to create one window context with specific window type and display and use it everywhere it's needed.

After Build.VERSION_CODES.S, window context provides the capability to receive configuration changes for existing token by overriding the token of the android.view.WindowManager.LayoutParams passed in WindowManager.addView(View, LayoutParams). This is useful when an application needs to attach its window to an existing activity for window token sharing use-case.

Note that the window context in Build.VERSION_CODES.R didn't have this capability. This is a no-op for the window context in Build.VERSION_CODES.R.

Below is sample code to attach an existing token to a window context:
final DisplayManager dm = anyContext.getSystemService(DisplayManager.class);
  final Display primaryDisplay = dm.getDisplay(DEFAULT_DISPLAY);
  final Context windowContext = anyContext.createWindowContext(primaryDisplay,
          TYPE_APPLICATION, null);
 
  // Get an existing token.
  final IBinder existingToken = activity.getWindow().getAttributes().token;
 
  // The types used in addView() and createWindowContext() must match.
  final WindowManager.LayoutParams params = new WindowManager.LayoutParams(TYPE_APPLICATION);
  params.token = existingToken;
 
  // After WindowManager#addView(), the server side will extract the provided token from
  // LayoutParams#token (existingToken in the sample code), and switch to propagate
  // configuration changes from the node associated with the provided token.
  windowContext.getSystemService(WindowManager.class).addView(overlayView, mParams);
  

After Build.VERSION_CODES.S, window context provides the capability to listen to its Configuration changes by calling registerComponentCallbacks(android.content.ComponentCallbacks), while other kinds of Context will register the ComponentCallbacks to its. Note that window context only propagate ComponentCallbacks.onConfigurationChanged(Configuration) callback. ComponentCallbacks.onLowMemory() or other callbacks in ComponentCallbacks2 won't be invoked.

Note that using android.app.Application or android.app.Service context for UI-related queries may result in layout or continuity issues on devices with variable screen sizes (e.g. foldables) or in multi-window modes, since these non-UI contexts may not reflect the Configuration changes for the visual container.

Array<String!>! databaseList()

Boolean deleteDatabase(name: String!)

Boolean deleteFile(name: String!)

Boolean deleteSharedPreferences(name: String!)

Unit enforceCallingOrSelfPermission(permission: String, message: String?)

If neither you nor the calling process of an IPC you are handling has been granted a particular permission, throw a SecurityException. This is the same as enforceCallingPermission, except it grants your own permissions if you are not currently processing an IPC. Use with care!

Unit enforceCallingOrSelfUriPermission(uri: Uri!, modeFlags: Int, message: String!)

Unit enforceCallingPermission(permission: String, message: String?)

If the calling process of an IPC you are handling has not been granted a particular permission, throw a SecurityException. This is basically the same as calling enforcePermission(java.lang.String,int,int,java.lang.String) with the pid and uid returned by android.os.Binder#getCallingPid and android.os.Binder#getCallingUid. One important difference is that if you are not currently processing an IPC, this function will always throw the SecurityException. This is done to protect against accidentally leaking permissions; you can use enforceCallingOrSelfPermission to avoid this protection.

Unit enforceCallingUriPermission(uri: Uri!, modeFlags: Int, message: String!)

Unit enforcePermission(permission: String, pid: Int, uid: Int, message: String?)

If the given permission is not allowed for a particular process and user ID running in the system, throw a SecurityException.

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

Enforce both a Uri and normal permission. This allows you to perform both enforcePermission and #enforceUriPermission in one call.

Array<String!>! fileList()

Context! getApplicationContext()

ApplicationInfo! getApplicationInfo()

AttributionSource getAttributionSource()

Context! getBaseContext()

File! getCacheDir()

ClassLoader! getClassLoader()

File! getCodeCacheDir()

ContentResolver! getContentResolver()

File! getDataDir()

File! getDatabasePath(name: String!)

Int getDeviceId()

File! getDir(name: String!, mode: Int)

Display! getDisplay()

Get the display this context is associated with. Applications should use this method with android.app.Activity or a context associated with a Display via createDisplayContext(android.view.Display) to get a display object associated with a Context, or android.hardware.display.DisplayManager#getDisplay to get a display object by id.

File? getExternalCacheDir()

Returns absolute path to application-specific directory on the primary shared/external storage device where the application can place cache files it owns. These files are internal to the application, and not typically visible to the user as media.

This is like getCacheDir() in that these files will be deleted when the application is uninstalled, however there are some important differences:

If a shared storage device is emulated (as determined by Environment.isExternalStorageEmulated(File)), its contents are backed by a private user data partition, which means there is little benefit to storing data here instead of the private directory returned by getCacheDir().

Starting in android.os.Build.VERSION_CODES#KITKAT, no permissions are required to read or write to the returned path; it's always accessible to the calling app. This only applies to paths generated for package name of the calling application. To access paths belonging to other packages, android.Manifest.permission#WRITE_EXTERNAL_STORAGE and/or android.Manifest.permission#READ_EXTERNAL_STORAGE are required.

On devices with multiple users (as described by UserManager), each user has their own isolated shared storage. Applications only have access to the shared storage for the user they're running as.

The returned path may change over time if different shared storage media is inserted, so only relative paths should be persisted.

Array<File!>! getExternalCacheDirs()

File? getExternalFilesDir(type: String?)

Returns the absolute path to the directory on the primary shared/external storage device where the application can place persistent files it owns. These files are internal to the applications, and not typically visible to the user as media.

This is like getFilesDir() in that these files will be deleted when the application is uninstalled, however there are some important differences:

If a shared storage device is emulated (as determined by Environment.isExternalStorageEmulated(File)), its contents are backed by a private user data partition, which means there is little benefit to storing data here instead of the private directories returned by getFilesDir(), etc.

Starting in android.os.Build.VERSION_CODES#KITKAT, no permissions are required to read or write to the returned path; it's always accessible to the calling app. This only applies to paths generated for package name of the calling application. To access paths belonging to other packages, android.Manifest.permission#WRITE_EXTERNAL_STORAGE and/or android.Manifest.permission#READ_EXTERNAL_STORAGE are required.

On devices with multiple users (as described by UserManager), each user has their own isolated shared storage. Applications only have access to the shared storage for the user they're running as.

The returned path may change over time if different shared storage media is inserted, so only relative paths should be persisted.

Here is an example of typical code to manipulate a file in an application's shared storage:

If you supply a non-null type to this function, the returned file will be a path to a sub-directory of the given type. Though these files are not automatically scanned by the media scanner, you can explicitly add them to the media database with MediaScannerConnection.scanFile. Note that this is not the same as Environment.getExternalStoragePublicDirectory(), which provides directories of media shared by all applications. The directories returned here are owned by the application, and their contents will be removed when the application is uninstalled. Unlike Environment.getExternalStoragePublicDirectory(), the directory returned here will be automatically created for you.

Here is an example of typical code to manipulate a picture in an application's shared storage and add it to the media database:

Array<File!>! getExternalFilesDirs(type: String!)

Array<File!>! getExternalMediaDirs()

File! getFileStreamPath(name: String!)

File! getFilesDir()

Executor! getMainExecutor()

Looper! getMainLooper()

File! getNoBackupFilesDir()

File! getObbDir()

Array<File!>! getObbDirs()

String! getPackageCodePath()

PackageManager! getPackageManager()

String! getPackageName()

String! getPackageResourcePath()

ContextParams? getParams()

Return the set of parameters which this Context was created with, if it was created via createContext(android.content.ContextParams).

SharedPreferences! getSharedPreferences(name: String!, mode: Int)

String? getSystemServiceName(serviceClass: Class<*>)

Drawable! getWallpaper()

Int getWallpaperDesiredMinimumHeight()

Int getWallpaperDesiredMinimumWidth()

Unit grantUriPermission(toPackage: String!, uri: Uri!, modeFlags: Int)

Boolean isDeviceProtectedStorage()

Boolean isRestricted()

Boolean moveDatabaseFrom(sourceContext: Context!, name: String!)

Boolean moveSharedPreferencesFrom(sourceContext: Context!, name: String!)

FileInputStream! openFileInput(name: String!)

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

Open a new private SQLiteDatabase associated with this Context's application package. Creates the database file if it doesn't exist.

Accepts input param: a concrete instance of DatabaseErrorHandler to be used to handle corruption when sqlite reports database corruption.

Drawable! peekWallpaper()

Unit registerComponentCallbacks(callback: ComponentCallbacks!)

Add a new ComponentCallbacks to the base application of the Context, which will be called at the same times as the ComponentCallbacks methods of activities and other components are called. Note that you must be sure to use unregisterComponentCallbacks when appropriate in the future; this will not be removed for you.

After Build.VERSION_CODES.TIRAMISU, the ComponentCallbacks will be registered to the base Context, and can be only used after attachBaseContext(android.content.Context). Users can still call to getApplicationContext().registerComponentCallbacks(ComponentCallbacks) to add ComponentCallbacks to the base application.

Unit registerDeviceIdChangeListener(executor: Executor, listener: IntConsumer)

Adds a new device ID changed listener to the Context, which will be called when the device association is changed by the system.

The callback can be called when an app is moved to a different device and the Context is not explicitly associated with a specific device.

When an application receives a device id update callback, this Context is guaranteed to also have an updated display ID(if any) and Configuration.

Intent? registerReceiver(receiver: BroadcastReceiver?, filter: IntentFilter!)

Register a BroadcastReceiver to be run in the main activity thread. The receiver will be called with any broadcast Intent that matches filter, in the main application thread.

The system may broadcast Intents that are "sticky" -- these stay around after the broadcast has finished, to be sent to any later registrations. If your IntentFilter matches one of these sticky Intents, that Intent will be returned by this function and sent to your receiver as if it had just been broadcast.

There may be multiple sticky Intents that match filter, in which case each of these will be sent to receiver. In this case, only one of these can be returned directly by the function; which of these that is returned is arbitrarily decided by the system.

If you know the Intent your are registering for is sticky, you can supply null for your receiver. In this case, no receiver is registered -- the function simply returns the sticky Intent that matches filter. In the case of multiple matches, the same rules as described above apply.

See BroadcastReceiver for more information on Intent broadcasts.

As of android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE, the system can place context-registered broadcasts in a queue while the app is in the cached state. When the app leaves the cached state, such as returning to the foreground, the system delivers any queued broadcasts. Multiple instances of certain broadcasts might be merged into one broadcast.

As of android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH, receivers registered with this method will correctly respect the Intent.setPackage(String) specified for an Intent being broadcast. Prior to that, it would be ignored and delivered to all matching registered receivers. Be careful if using this for security.

For apps targeting android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE, either RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED must be specified if the receiver is not being registered for system broadcasts or a SecurityException will be thrown. See registerReceiver(android.content.BroadcastReceiver,android.content.IntentFilter,int) to register a receiver with flags.

Note: this method cannot be called from a BroadcastReceiver component; that is, from a BroadcastReceiver that is declared in an application's manifest. It is okay, however, to call this method from another BroadcastReceiver that has itself been registered at run time with #registerReceiver, since the lifetime of such a registered BroadcastReceiver is tied to the object that registered it.

Intent? registerReceiver(receiver: BroadcastReceiver?, filter: IntentFilter!, flags: Int)

Register to receive intent broadcasts, with the receiver optionally being exposed to Instant Apps. See registerReceiver(android.content.BroadcastReceiver,android.content.IntentFilter) for more information. By default Instant Apps cannot interact with receivers in other applications, this allows you to expose a receiver that Instant Apps can interact with.

See BroadcastReceiver for more information on Intent broadcasts.

As of android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE, the system can place context-registered broadcasts in a queue while the app is in the cached state. When the app leaves the cached state, such as returning to the foreground, the system delivers any queued broadcasts. Multiple instances of certain broadcasts might be merged into one broadcast.

As of android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH, receivers registered with this method will correctly respect the Intent.setPackage(String) specified for an Intent being broadcast. Prior to that, it would be ignored and delivered to all matching registered receivers. Be careful if using this for security.

Intent? registerReceiver(receiver: BroadcastReceiver?, filter: IntentFilter!, broadcastPermission: String?, scheduler: Handler?)

Register to receive intent broadcasts, to run in the context of scheduler. See registerReceiver(android.content.BroadcastReceiver,android.content.IntentFilter) for more information. This allows you to enforce permissions on who can broadcast intents to your receiver, or have the receiver run in a different thread than the main application thread.

See BroadcastReceiver for more information on Intent broadcasts.

As of android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE, the system can place context-registered broadcasts in a queue while the app is in the cached state. When the app leaves the cached state, such as returning to the foreground, the system delivers any queued broadcasts. Multiple instances of certain broadcasts might be merged into one broadcast.

As of android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH, receivers registered with this method will correctly respect the Intent.setPackage(String) specified for an Intent being broadcast. Prior to that, it would be ignored and delivered to all matching registered receivers. Be careful if using this for security.

For apps targeting android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE, either RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED must be specified if the receiver is not being registered for system broadcasts or a SecurityException will be thrown. See registerReceiver(android.content.BroadcastReceiver,android.content.IntentFilter,java.lang.String,android.os.Handler,int) to register a receiver with flags.

Intent? registerReceiver(receiver: BroadcastReceiver?, filter: IntentFilter!, broadcastPermission: String?, scheduler: Handler?, flags: Int)

Register to receive intent broadcasts, to run in the context of scheduler. See registerReceiver(android.content.BroadcastReceiver,android.content.IntentFilter,int) and registerReceiver(android.content.BroadcastReceiver,android.content.IntentFilter,java.lang.String,android.os.Handler) for more information.

See BroadcastReceiver for more information on Intent broadcasts.

As of android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE, the system can place context-registered broadcasts in a queue while the app is in the cached state. When the app leaves the cached state, such as returning to the foreground, the system delivers any queued broadcasts. Multiple instances of certain broadcasts might be merged into one broadcast.

As of android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH, receivers registered with this method will correctly respect the Intent.setPackage(String) specified for an Intent being broadcast. Prior to that, it would be ignored and delivered to all matching registered receivers. Be careful if using this for security.

Unit removeStickyBroadcast(intent: Intent!)

Unit removeStickyBroadcastAsUser(intent: Intent!, user: UserHandle!)

Unit revokeSelfPermissionsOnKill(permissions: MutableCollection<String!>)

Triggers the revocation of one or more permissions for the calling package. A package is only able to revoke runtime permissions. If a permission is not currently granted, it is ignored and will not get revoked (even if later granted by the user). Ultimately, you should never make assumptions about a permission status as users may grant or revoke them at any time.

Background permissions which have no corresponding foreground permission still granted once the revocation is effective will also be revoked.

The revocation happens asynchronously and kills all processes running in the calling UID. It will be triggered once it is safe to do so. In particular, it will not be triggered as long as the package remains in the foreground, or has any active manifest components (e.g. when another app is accessing a content provider in the package).

If you want to revoke the permissions right away, you could call System.exit() in Handler.postDelayed with a delay to allow completion of async IPC, But System.exit() could affect other apps that are accessing your app at the moment. For example, apps accessing a content provider in your app will all crash.

Note that the settings UI shows a permission group as granted as long as at least one permission in the group is granted. If you want the user to observe the revocation in the settings, you should revoke every permission in the target group. To learn the current list of permissions in a group, you may use PackageManager.getGroupOfPlatformPermission(String, Executor, Consumer) and PackageManager.getPlatformPermissionsForGroup(String, Executor, Consumer). This list of permissions may evolve over time, so it is recommended to check whether it contains any permission you wish to retain before trying to revoke an entire group.

Unit revokeUriPermission(uri: Uri!, modeFlags: Int)

Unit revokeUriPermission(targetPackage: String!, uri: Uri!, modeFlags: Int)

Unit sendBroadcast(intent: Intent!)

Unit sendBroadcast(intent: Intent!, receiverPermission: String?)

Broadcast the given intent to all interested BroadcastReceivers, allowing an optional required permission to be enforced. This call is asynchronous; it returns immediately, and you will continue executing while the receivers are run. No results are propagated from receivers and receivers can not abort the broadcast. If you want to allow receivers to propagate results or abort the broadcast, you must send an ordered broadcast using sendOrderedBroadcast(android.content.Intent,java.lang.String).

See BroadcastReceiver for more information on Intent broadcasts.

Unit sendBroadcast(intent: Intent, receiverPermission: String?, options: Bundle?)

Broadcast the given intent to all interested BroadcastReceivers, allowing an optional required permission to be enforced. This call is asynchronous; it returns immediately, and you will continue executing while the receivers are run. No results are propagated from receivers and receivers can not abort the broadcast. If you want to allow receivers to propagate results or abort the broadcast, you must send an ordered broadcast using sendOrderedBroadcast(android.content.Intent,java.lang.String).

See BroadcastReceiver for more information on Intent broadcasts.

Unit sendBroadcastAsUser(intent: Intent!, user: UserHandle!)

Unit sendBroadcastAsUser(intent: Intent!, user: UserHandle!, receiverPermission: String?)

Unit sendOrderedBroadcast(intent: Intent, initialCode: Int, receiverPermission: String?, receiverAppOp: String?, resultReceiver: BroadcastReceiver?, scheduler: Handler?, initialData: String?, initialExtras: Bundle?, options: Bundle?)

Unit sendOrderedBroadcast(intent: Intent!, receiverPermission: String?)

Broadcast the given intent to all interested BroadcastReceivers, delivering them one at a time to allow more preferred receivers to consume the broadcast before it is delivered to less preferred receivers. This call is asynchronous; it returns immediately, and you will continue executing while the receivers are run.

See BroadcastReceiver for more information on Intent broadcasts.

Unit sendOrderedBroadcast(intent: Intent, receiverPermission: String?, resultReceiver: BroadcastReceiver?, scheduler: Handler?, initialCode: Int, initialData: String?, initialExtras: Bundle?)

Version of sendBroadcast(android.content.Intent) that allows you to receive data back from the broadcast. This is accomplished by supplying your own BroadcastReceiver when calling, which will be treated as a final receiver at the end of the broadcast -- its BroadcastReceiver.onReceive method will be called with the result values collected from the other receivers. The broadcast will be serialized in the same way as calling sendOrderedBroadcast(android.content.Intent,java.lang.String).

Like sendBroadcast(android.content.Intent), this method is asynchronous; it will return before resultReceiver.onReceive() is called.

See BroadcastReceiver for more information on Intent broadcasts.

Unit sendOrderedBroadcast(intent: Intent, receiverPermission: String?, options: Bundle?)

Broadcast the given intent to all interested BroadcastReceivers, delivering them one at a time to allow more preferred receivers to consume the broadcast before it is delivered to less preferred receivers. This call is asynchronous; it returns immediately, and you will continue executing while the receivers are run.

See BroadcastReceiver for more information on Intent broadcasts.

Unit sendOrderedBroadcast(intent: Intent, receiverPermission: String?, options: Bundle?, resultReceiver: BroadcastReceiver?, scheduler: Handler?, initialCode: Int, initialData: String?, initialExtras: Bundle?)

Version of sendBroadcast(android.content.Intent) that allows you to receive data back from the broadcast. This is accomplished by supplying your own BroadcastReceiver when calling, which will be treated as a final receiver at the end of the broadcast -- its BroadcastReceiver.onReceive method will be called with the result values collected from the other receivers. The broadcast will be serialized in the same way as calling sendOrderedBroadcast(android.content.Intent,java.lang.String).

Like sendBroadcast(android.content.Intent), this method is asynchronous; it will return before resultReceiver.onReceive() is called.

See BroadcastReceiver for more information on Intent broadcasts.

Unit sendOrderedBroadcast(intent: Intent, receiverPermission: String?, receiverAppOp: String?, resultReceiver: BroadcastReceiver?, scheduler: Handler?, initialCode: Int, initialData: String?, initialExtras: Bundle?)

Version of sendOrderedBroadcast(android.content.Intent,java.lang.String,android.content.BroadcastReceiver,android.os.Handler,int,java.lang.String,android.os.Bundle) that allows you to specify the App Op to enforce restrictions on which receivers the broadcast will be sent to.

See BroadcastReceiver for more information on Intent broadcasts.

Unit sendOrderedBroadcastAsUser(intent: Intent!, user: UserHandle!, receiverPermission: String?, resultReceiver: BroadcastReceiver?, scheduler: Handler?, initialCode: Int, initialData: String?, initialExtras: Bundle?)

Version of sendOrderedBroadcast(android.content.Intent,java.lang.String,android.content.BroadcastReceiver,android.os.Handler,int,java.lang.String,android.os.Bundle) that allows you to specify the user the broadcast will be sent to. This is not available to applications that are not pre-installed on the system image.

See BroadcastReceiver for more information on Intent broadcasts.
Requires android.Manifest.permission.INTERACT_ACROSS_USERS

Unit sendStickyBroadcast(intent: Intent!)

Unit sendStickyBroadcast(intent: Intent, options: Bundle?)

Perform a sendBroadcast(android.content.Intent) that is "sticky," meaning the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(android.content.BroadcastReceiver,android.content.IntentFilter). In all other ways, this behaves the same as sendBroadcast(android.content.Intent).

Unit sendStickyBroadcastAsUser(intent: Intent!, user: UserHandle!)

Unit sendStickyOrderedBroadcast(intent: Intent!, resultReceiver: BroadcastReceiver?, scheduler: Handler?, initialCode: Int, initialData: String?, initialExtras: Bundle?)

Version of #sendStickyBroadcast that allows you to receive data back from the broadcast. This is accomplished by supplying your own BroadcastReceiver when calling, which will be treated as a final receiver at the end of the broadcast -- its BroadcastReceiver.onReceive method will be called with the result values collected from the other receivers. The broadcast will be serialized in the same way as calling sendOrderedBroadcast(android.content.Intent,java.lang.String).

Like sendBroadcast(android.content.Intent), this method is asynchronous; it will return before resultReceiver.onReceive() is called. Note that the sticky data stored is only the data you initially supply to the broadcast, not the result of any changes made by the receivers.

See BroadcastReceiver for more information on Intent broadcasts.
Requires android.Manifest.permission#BROADCAST_STICKY

Unit sendStickyOrderedBroadcastAsUser(intent: Intent!, user: UserHandle!, resultReceiver: BroadcastReceiver?, scheduler: Handler?, initialCode: Int, initialData: String?, initialExtras: Bundle?)

Version of sendStickyOrderedBroadcast(android.content.Intent,android.content.BroadcastReceiver,android.os.Handler,int,java.lang.String,android.os.Bundle) that allows you to specify the user the broadcast will be sent to. This is not available to applications that are not pre-installed on the system image.

See BroadcastReceiver for more information on Intent broadcasts.
Requires android.Manifest.permission.INTERACT_ACROSS_USERS and android.Manifest.permission#BROADCAST_STICKY

Unit setWallpaper(bitmap: Bitmap!)

Unit setWallpaper(data: InputStream!)

Unit startActivities(intents: Array<Intent!>!)

Unit startActivities(intents: Array<Intent!>!, options: Bundle?)

Launch multiple new activities. This is generally the same as calling startActivity(android.content.Intent) for the first Intent in the array, that activity during its creation calling startActivity(android.content.Intent) for the second entry, etc. Note that unlike that approach, generally none of the activities except the last in the array will be created at this point, but rather will be created when the user first visits them (due to pressing back from the activity on top).

This method throws ActivityNotFoundException if there was no Activity found for any given Intent. In this case the state of the activity stack is undefined (some Intents in the list may be on it, some not), so you probably want to avoid such situations.

Unit startActivity(intent: Intent!)

Unit startActivity(intent: Intent!, options: Bundle?)

Launch a new activity. You will not receive any information about when the activity exits.

Note that if this method is being called from outside of an android.app.Activity Context, then the Intent must include the Intent.FLAG_ACTIVITY_NEW_TASK launch flag. This is because, without being started from an existing Activity, there is no existing task in which to place the new activity and thus it needs to be placed in its own separate task.

This method throws ActivityNotFoundException if there was no Activity found to run the given Intent.

ComponentName? startForegroundService(service: Intent!)

Similar to startService(android.content.Intent), but with an implicit promise that the Service will call startForeground(int, android.app.Notification) once it begins running. The service is given an amount of time comparable to the ANR interval to do this, otherwise the system will automatically crash the process, in which case an internal exception ForegroundServiceDidNotStartInTimeException is logged on logcat on devices running SDK Version android.os.Build.VERSION_CODES#S or later. On older Android versions, an internal exception RemoteServiceException is logged instead, with a corresponding message.

Unlike the ordinary startService(android.content.Intent), this method can be used at any time, regardless of whether the app hosting the service is in a foreground state.

Note: Beginning with SDK Version android.os.Build.VERSION_CODES#S, apps targeting SDK Version android.os.Build.VERSION_CODES#S or higher are not allowed to start foreground services from the background. See Behavior changes: Apps targeting Android 12 for more details.

Boolean startInstrumentation(className: ComponentName, profileFile: String?, arguments: Bundle?)

Start executing an android.app.Instrumentation class. The given Instrumentation component will be run by killing its target application (if currently running), starting the target process, instantiating the instrumentation component, and then letting it drive the application.

This function is not synchronous -- it returns as soon as the instrumentation has started and while it is running.

Instrumentation is normally only allowed to run against a package that is either unsigned or signed with a signature that the the instrumentation package is also signed with (ensuring the target trusts the instrumentation).

Unit startIntentSender(intent: IntentSender!, fillInIntent: Intent?, flagsMask: Int, flagsValues: Int, extraFlags: Int)

Same as startIntentSender(android.content.IntentSender,android.content.Intent,int,int,int,android.os.Bundle) with no options specified.

Unit startIntentSender(intent: IntentSender!, fillInIntent: Intent?, flagsMask: Int, flagsValues: Int, extraFlags: Int, options: Bundle?)

Like startActivity(android.content.Intent,android.os.Bundle), but taking a IntentSender to start. If the IntentSender is for an activity, that activity will be started as if you had called the regular startActivity(android.content.Intent) here; otherwise, its associated action will be executed (such as sending a broadcast) as if you had called android.content.IntentSender#sendIntent on it.

ComponentName? startService(service: Intent!)

Request that a given application service be started. The Intent should either contain the complete class name of a specific service implementation to start, or a specific package name to target. If the Intent is less specified, it logs a warning about this. In this case any of the multiple matching services may be used. If this service is not already running, it will be instantiated and started (creating a process for it if needed); if it is running then it remains running.

Every call to this method will result in a corresponding call to the target service's android.app.Service#onStartCommand method, with the intent given here. This provides a convenient way to submit jobs to a service without having to bind and call on to its interface.

Using startService() overrides the default service lifetime that is managed by #bindService: it requires the service to remain running until stopService is called, regardless of whether any clients are connected to it. Note that calls to startService() do not nest: no matter how many times you call startService(), a single call to stopService will stop it.

The system attempts to keep running services around as much as possible. The only time they should be stopped is if the current foreground application is using so many resources that the service needs to be killed. If any errors happen in the service's process, it will automatically be restarted.

This function will throw SecurityException if you do not have permission to start the given service.

Note: Each call to startService() results in significant work done by the system to manage service lifecycle surrounding the processing of the intent, which can take multiple milliseconds of CPU time. Due to this cost, startService() should not be used for frequent intent delivery to a service, and only for scheduling significant work. Use #bindService for high frequency calls.

Beginning with SDK Version android.os.Build.VERSION_CODES#O, apps targeting SDK Version android.os.Build.VERSION_CODES#O or higher are not allowed to start background services from the background. See Background Execution Limits for more details.

Note: Beginning with SDK Version android.os.Build.VERSION_CODES#S, apps targeting SDK Version android.os.Build.VERSION_CODES#S or higher are not allowed to start foreground services from the background. See Behavior changes: Apps targeting Android 12 for more details.

Boolean stopService(name: Intent!)

Unit unbindService(conn: ServiceConnection)

Unit unregisterComponentCallbacks(callback: ComponentCallbacks!)

Remove a ComponentCallbacks object that was previously registered with registerComponentCallbacks(android.content.ComponentCallbacks).

After Build.VERSION_CODES.TIRAMISU, the ComponentCallbacks will be unregistered to the base Context, and can be only used after attachBaseContext(android.content.Context)

Unit unregisterDeviceIdChangeListener(listener: IntConsumer)

Removes a device ID changed listener from the Context. It's a no-op if the listener is not already registered.

Unit unregisterReceiver(receiver: BroadcastReceiver!)

Unit updateServiceGroup(conn: ServiceConnection, group: Int, importance: Int)

Boolean bindIsolatedService(service: Intent, flags: Context.BindServiceFlags, instanceName: String, executor: Executor, conn: ServiceConnection)

See bindIsolatedService(android.content.Intent,int,java.lang.String,java.util.concurrent.Executor,android.content.ServiceConnection) Call BindServiceFlags.of(long) to obtain a BindServiceFlags object.

Int getColor(id: Int)

Returns a color associated with a particular resource ID and styled for the current theme.

ColorStateList getColorStateList(id: Int)

Returns a color state list associated with a particular resource ID and styled for the current theme.

Drawable? getDrawable(id: Int)

Returns a drawable object associated with a particular resource ID and styled for the current theme.

String getString(resId: Int)

Returns a localized string from the application's package's default string table.

String getString(resId: Int, vararg formatArgs: Any!)

Returns a localized formatted string from the application's package's default string table, substituting the format arguments as defined in java.util.Formatter and java.lang.String#format.

T getSystemService(serviceClass: Class<T>)

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

Currently available classes are: android.view.WindowManager, android.view.LayoutInflater, android.app.ActivityManager, android.os.PowerManager, android.app.AlarmManager, android.app.NotificationManager, android.app.KeyguardManager, android.location.LocationManager, android.app.SearchManager, android.os.Vibrator, android.net.ConnectivityManager, android.net.wifi.WifiManager, android.media.AudioManager, android.media.MediaRouter, android.telephony.TelephonyManager, android.telephony.SubscriptionManager, android.view.inputmethod.InputMethodManager, android.app.UiModeManager, android.app.DownloadManager, android.os.BatteryManager, android.app.job.JobScheduler, android.app.usage.NetworkStatsManager, android.content.pm.verify.domain.DomainVerificationManager, android.view.displayhash.DisplayHashManager android.security.authenticationpolicy.AuthenticationPolicyManager.

Note: System services obtained via this API may be closely associated with the Context in which they are obtained from. In general, do not share the service objects between various different contexts (Activities, Applications, Services, Providers, etc.)

Note: Instant apps, for which PackageManager.isInstantApp() returns true, don't have access to the following system services: DEVICE_POLICY_SERVICE, FINGERPRINT_SERVICE, KEYGUARD_SERVICE, SHORTCUT_SERVICE, USB_SERVICE, WALLPAPER_SERVICE, WIFI_P2P_SERVICE, WIFI_SERVICE, WIFI_AWARE_SERVICE. For these services this method will return null. Generally, if you are running as an instant app you should always check whether the result of this method is null.

CharSequence getText(resId: Int)

Return a localized, styled CharSequence from the application's package's default string table.

TypedArray obtainStyledAttributes(set: AttributeSet?, attrs: IntArray)

Retrieve styled attribute information in this Context's theme. See android.content.res.Resources.Theme#obtainStyledAttributes(AttributeSet, int[], int, int) for more information.

TypedArray obtainStyledAttributes(set: AttributeSet?, attrs: IntArray, defStyleAttr: Int, defStyleRes: Int)

Retrieve styled attribute information in this Context's theme. See android.content.res.Resources.Theme#obtainStyledAttributes(AttributeSet, int[], int, int) for more information.

TypedArray obtainStyledAttributes(resid: Int, attrs: IntArray)

Retrieve styled attribute information in this Context's theme. See android.content.res.Resources.Theme#obtainStyledAttributes(int, int[]) for more information.

TypedArray obtainStyledAttributes(attrs: IntArray)

Retrieve styled attribute information in this Context's theme. See android.content.res.Resources.Theme#obtainStyledAttributes(int[]) for more information.

Unit revokeSelfPermissionOnKill(permName: String)

Triggers the asynchronous revocation of a runtime permission. If the permission is not currently granted, nothing happens (even if later granted by the user).

Unit sendBroadcastWithMultiplePermissions(intent: Intent, receiverPermissions: Array<String!>)

Broadcast the given intent to all interested BroadcastReceivers, allowing an array of required permissions to be enforced. This call is asynchronous; it returns immediately, and you will continue executing while the receivers are run. No results are propagated from receivers and receivers can not abort the broadcast. If you want to allow receivers to propagate results or abort the broadcast, you must send an ordered broadcast using sendOrderedBroadcast(android.content.Intent,java.lang.String).

See BroadcastReceiver for more information on Intent broadcasts.

ListAdapter! getListAdapter()

Get the ListAdapter associated with this activity's ListView.

ListView! getListView()

Get the activity's list view widget.

Long getSelectedItemId()

Get the cursor row ID of the currently selected list item.

Int getSelectedItemPosition()

Get the position of the currently selected list item.

Unit onContentChanged()

Updates the screen state (current list and other views) when the content changes.

Unit onDestroy()

Unit onRestoreInstanceState(state: Bundle)

Ensures the list view has been created before Activity restores all of the view states.

Unit setListAdapter(adapter: ListAdapter!)

Provide the cursor for the list view.

Unit setSelection(position: Int)

Set the currently selected list item to the specified position with the adapter's data

Unit onConfigurationChanged(newConfig: Configuration)

Called by the system when the device configuration changes while your component is running. Note that, unlike activities, other components are never restarted when a configuration changes: they must always deal with the results of the change, such as by re-retrieving resources.

At the time that this function has been called, your Resources object will have been updated to return resource values matching the new configuration.

For more information, read Handling Runtime Changes.

Unit onLowMemory()

This is called when the overall system is running low on memory, and actively running processes should trim their memory usage. While the exact point at which this will be called is not defined, generally it will happen when all background process have been killed. That is, before reaching the point of killing processes hosting service and foreground UI that we would like to avoid killing.

Unit onPointerCaptureChanged(hasCapture: Boolean)

Called when pointer capture is enabled or disabled for the current window.

Inherited properties

Public constructors

LauncherActivity

LauncherActivity()

Public methods

makeListItems

Added in API level 3
Deprecated in API level 30
open fun makeListItems(): MutableList<LauncherActivity.ListItem!>!

Deprecated: Deprecated in Java.

Perform the query to determine which results to show and return a list of them.

setTitle

Added in API level 1
open fun setTitle(titleId: Int): Unit

Deprecated: Deprecated in Java.

setTitle

Added in API level 1
open fun setTitle(title: CharSequence!): Unit

Deprecated: Deprecated in Java.

Protected methods

getTargetIntent

Added in API level 1
protected open fun getTargetIntent(): Intent!

Deprecated: Deprecated in Java.

Get the base intent to use when running PackageManager.queryIntentActivities(Intent, int).

intentForPosition

Added in API level 3
Deprecated in API level 30
protected open fun intentForPosition(position: Int): Intent!

Deprecated: Deprecated in Java.

Return the actual Intent for a specific position in our android.widget.ListView.

Parameters
position Int: The item whose Intent to return

itemForPosition

Added in API level 4
Deprecated in API level 30
protected open fun itemForPosition(position: Int): LauncherActivity.ListItem!

Deprecated: Deprecated in Java.

Return the ListItem for a specific position in our android.widget.ListView.

Parameters
position Int: The item to return

onCreate

Added in API level 1
protected open fun onCreate(icicle: Bundle?): Unit

Deprecated: Deprecated in Java.

Parameters
savedInstanceState If the activity is being re-initialized after previously being shut down then this Bundle contains the data it most recently supplied in #onSaveInstanceState. Note: Otherwise it is null.

onListItemClick

Added in API level 1
protected open fun onListItemClick(
    l: ListView!,
    v: View!,
    position: Int,
    id: Long
): Unit

Deprecated: Deprecated in Java.

Parameters
l ListView!: The ListView where the click happened
v View!: The view that was clicked within the ListView
position Int: The position of the view in the list
id Long: The row id of the item that was clicked

onQueryPackageManager

Added in API level 5
Deprecated in API level 30
protected open fun onQueryPackageManager(queryIntent: Intent!): MutableList<ResolveInfo!>!

Deprecated: Deprecated in Java.

Perform query on package manager for list items. The default implementation queries for activities.

onSetContentView

Added in API level 5
Deprecated in API level 30
protected open fun onSetContentView(): Unit

Deprecated: Deprecated in Java.

Override to call setContentView() with your own content view to customize the list layout.