Added in API level 4

AccessibilityService


abstract class AccessibilityService : Service

Accessibility services should only be used to assist users with disabilities in using Android devices and apps. They run in the background and receive callbacks by the system when AccessibilityEvents are fired. Such events denote some state transition in the user interface, for example, the focus has changed, a button has been clicked, etc. Such a service can optionally request the capability for querying the content of the active window. Development of an accessibility service requires extending this class and implementing its abstract methods.

Lifecycle

The lifecycle of an accessibility service is managed exclusively by the system and follows the established service life cycle. Starting an accessibility service is triggered exclusively by the user explicitly turning the service on in device settings. After the system binds to a service, it calls AccessibilityService.onServiceConnected(). This method can be overridden by clients that want to perform post binding setup.

An accessibility service stops either when the user turns it off in device settings or when it calls AccessibilityService.disableSelf().

Declaration

An accessibility is declared as any other service in an AndroidManifest.xml, but it must do two things:

If either of these items is missing, the system will ignore the accessibility service. Following is an example declaration:

<service android:name=".MyAccessibilityService"
          android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
      <intent-filter>
          <action android:name="android.accessibilityservice.AccessibilityService" />
      </intent-filter>
      . . .
  </service>

Configuration

An accessibility service can be configured to receive specific types of accessibility events, listen only to specific packages, get events from each type only once in a given time frame, retrieve window content, specify a settings activity, etc.

There are two approaches for configuring an accessibility service:

Retrieving window content

A service can specify in its declaration that it can retrieve window content which is represented as a tree of AccessibilityWindowInfo and AccessibilityNodeInfo objects. Note that declaring this capability requires that the service declares its configuration via an XML resource referenced by SERVICE_META_DATA.

Window content may be retrieved with AccessibilityEvent.getSource(), AccessibilityService.findFocus(int), AccessibilityService.getWindows(), or AccessibilityService.getRootInActiveWindow().

Note An accessibility service may have requested to be notified for a subset of the event types, and thus be unaware when the node hierarchy has changed. It is also possible for a node to contain outdated information because the window content may change at any time.

Drawing Accessibility Overlays

Accessibility services can draw overlays on top of existing screen contents. Accessibility overlays can be used to visually highlight items on the screen e.g. indicate the current item with accessibility focus. Overlays can also offer the user a way to interact with the service directly and quickly customize the service's behavior.

Accessibility overlays can be attached to a particular window or to the display itself. Attaching an overlay to a window allows the overly to move, grow and shrink as the window does. The overlay will maintain the same relative position within the window bounds as the window moves. The overlay will also maintain the same relative position within the window bounds if the window is resized. To attach an overlay to a window, use #attachAccessibilityOverlayToWindow. Attaching an overlay to the display means that the overlay is independent of the active windows on that display. To attach an overlay to a display, use #attachAccessibilityOverlayToDisplay.

When positioning an overlay that is attached to a window, the service must use window coordinates. In order to position an overlay on top of an existing UI element it is necessary to know the bounds of that element in window coordinates. To find the bounds in window coordinates of an element, find the corresponding AccessibilityNodeInfo as discussed above and call AccessibilityNodeInfo.getBoundsInWindow.

Notification strategy

All accessibility services are notified of all events they have requested, regardless of their feedback type.

Note: The event notification timeout is useful to avoid propagating events to the client too frequently since this is accomplished via an expensive interprocess call. One can think of the timeout as a criteria to determine when event generation has settled down.

Event types

Feedback types

Summary

Nested classes
abstract

Class used to report status of dispatched gestures

Used to control and query the state of display magnification.

Can be used to construct a bitmap of the screenshot or any other operations for AccessibilityService.takeScreenshot API.

Used to control, query, and listen for changes to the soft keyboard show mode.

abstract

Interface used to report status of taking screenshot.

Constants
static Int

The status of taking screenshot is failure and the reason is internal error.

static Int

The status of taking screenshot is failure and the reason is that too little time has elapsed since the last screenshot.

static Int

The status of taking screenshot is failure and the reason is invalid display Id.

static Int

The status of taking screenshot is failure and the reason is invalid accessibility window Id.

static Int

The status of taking screenshot is failure and the reason is no accessibility access.

static Int

The status of taking screenshot is failure and the reason is the window contains secure content.

static Int

The user has performed a two-finger double tap gesture on the touch screen.

static Int

The user has performed a two-finger double tap and hold gesture on the touch screen.

static Int

The user has performed a two-finger single tap gesture on the touch screen.

static Int

The user has performed a two-finger swipe down gesture on the touch screen.

static Int

The user has performed a two-finger swipe left gesture on the touch screen.

static Int

The user has performed a two-finger swipe right gesture on the touch screen.

static Int

The user has performed a two-finger swipe up gesture on the touch screen.

static Int

The user has performed a two-finger triple tap gesture on the touch screen.

static Int

The user has performed a two-finger triple-tap and hold gesture on the touch screen.

static Int

The user has performed a three-finger double tap gesture on the touch screen.

static Int

The user has performed a three-finger double tap and hold gesture on the touch screen.

static Int

The user has performed a three-finger single tap gesture on the touch screen.

static Int

The user has performed a three-finger single-tap and hold gesture on the touch screen.

static Int

The user has performed a three-finger swipe down gesture on the touch screen.

static Int

The user has performed a three-finger swipe left gesture on the touch screen.

static Int

The user has performed a three-finger swipe right gesture on the touch screen.

static Int

The user has performed a three-finger swipe up gesture on the touch screen.

static Int

The user has performed a three-finger triple tap gesture on the touch screen.

static Int

The user has performed a three-finger triple-tap and hold gesture on the touch screen.

static Int

The user has performed a four-finger double tap gesture on the touch screen.

static Int

The user has performed a two-finger double tap and hold gesture on the touch screen.

static Int

The user has performed a four-finger single tap gesture on the touch screen.

static Int

The user has performed a four-finger swipe down gesture on the touch screen.

static Int

The user has performed a four-finger swipe left gesture on the touch screen.

static Int

The user has performed a four-finger swipe right gesture on the touch screen.

static Int

The user has performed a four-finger swipe up gesture on the touch screen.

static Int

The user has performed a four-finger triple tap gesture on the touch screen.

static Int

The user has performed a double tap gesture on the touch screen.

static Int

The user has performed a double tap and hold gesture on the touch screen.

static Int

The user has performed a swipe down gesture on the touch screen.

static Int

The user has performed a down and left gesture on the touch screen.

static Int

The user has performed a down and right gesture on the touch screen.

static Int

The user has performed a swipe down and up gesture on the touch screen.

static Int

The user has performed a swipe left gesture on the touch screen.

static Int

The user has performed a left and down gesture on the touch screen.

static Int

The user has performed a swipe left and right gesture on the touch screen.

static Int

The user has performed a left and up gesture on the touch screen.

static Int

The user has performed a swipe right gesture on the touch screen.

static Int

The user has performed a right and down gesture on the touch screen.

static Int

The user has performed a swipe right and left gesture on the touch screen.

static Int

The user has performed a right and up gesture on the touch screen.

static Int

The user has performed a swipe up gesture on the touch screen.

static Int

The user has performed a swipe up and down gesture on the touch screen.

static Int

The user has performed an up and left gesture on the touch screen.

static Int

The user has performed an up and right gesture on the touch screen.

static Int

The user has performed an unrecognized gesture on the touch screen.

static Int

Action to show Launcher's all apps.

static Int

Action to trigger the Accessibility Button

static Int

Action to bring up the Accessibility Button's chooser menu

static Int

Action to trigger the Accessibility Shortcut.

static Int

Action to go back.

static Int

Action to dismiss the notification shade

static Int

Action to trigger dpad center keyevent.

static Int

Action to trigger dpad down keyevent.

static Int

Action to trigger dpad left keyevent.

static Int

Action to trigger dpad right keyevent.

static Int

Action to trigger dpad up keyevent.

static Int

Action to go home.

static Int

Action to send the KEYCODE_HEADSETHOOK KeyEvent, which is used to answer and hang up calls and play and stop media.

static Int

Action to lock the screen

static Int

Action to trigger media play/pause key event.

static Int

Action to trigger menu key event.

static Int

Action to open the notifications.

static Int

Action to open the power long-press dialog.

static Int

Action to open the quick settings.

static Int

Action to toggle showing the overview of recent apps.

static Int

Action to take a screenshot

static Int

Action to toggle docking the current app's window.

static Int

Result code indicating the overlay could not be attached due to an internal error and not because of problems with the input.

static Int

Result code indicating the overlay could not be attached because the specified display or window id was invalid.

static Int

Result code indicating the overlay was successfully attached.

static String

The Intent that must be declared as handled by the service.

static String

Name under which an AccessibilityService component publishes information about itself.

static Int

Allow the system to control when the soft keyboard is shown.

static Int

Never show the soft keyboard.

static Int

Allow the soft keyboard to be shown, even if a hard keyboard is connected

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 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_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 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 START_CONTINUATION_MASK

Bits returned by onStartCommand describing how to continue the service if it is killed. May be START_STICKY, START_NOT_STICKY, START_REDELIVER_INTENT, or START_STICKY_COMPATIBILITY.

Int START_FLAG_REDELIVERY

This flag is set in onStartCommand if the Intent is a re-delivery of a previously delivered intent, because the service had previously returned START_REDELIVER_INTENT but had been killed before calling stopSelf(int) for that Intent.

Int START_FLAG_RETRY

This flag is set in onStartCommand if the Intent is a retry because the original attempt never got to or returned from onStartCommand(android.content.Intent,int,int).

Int START_NOT_STICKY

Constant to return from onStartCommand: if this service's process is killed while it is started (after returning from onStartCommand), and there are no new start intents to deliver to it, then take the service out of the started state and don't recreate until a future explicit call to Context.startService(Intent). The service will not receive a onStartCommand(android.content.Intent,int,int) call with a null Intent because it will not be restarted if there are no pending Intents to deliver.

This mode makes sense for things that want to do some work as a result of being started, but can be stopped when under memory pressure and will explicit start themselves again later to do more work. An example of such a service would be one that polls for data from a server: it could schedule an alarm to poll every N minutes by having the alarm start its service. When its onStartCommand is called from the alarm, it schedules a new alarm for N minutes later, and spawns a thread to do its networking. If its process is killed while doing that check, the service will not be restarted until the alarm goes off.

Int START_REDELIVER_INTENT

Constant to return from onStartCommand: if this service's process is killed while it is started (after returning from onStartCommand), then it will be scheduled for a restart and the last delivered Intent re-delivered to it again via onStartCommand. This Intent will remain scheduled for redelivery until the service calls stopSelf(int) with the start ID provided to onStartCommand. The service will not receive a onStartCommand(android.content.Intent,int,int) call with a null Intent because it will only be restarted if it is not finished processing all Intents sent to it (and any such pending events will be delivered at the point of restart).

Int START_STICKY

Constant to return from onStartCommand: if this service's process is killed while it is started (after returning from onStartCommand), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.

This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, such as a service performing background music playback.

Since Android version Build.VERSION_CODES.S, apps targeting Build.VERSION_CODES.S or above are disallowed to start a foreground service from the background, but the restriction doesn't impact restarts of a sticky foreground service. However, when apps start a sticky foreground service from the background, the same restriction still applies.

Int START_STICKY_COMPATIBILITY

Constant to return from onStartCommand: compatibility version of START_STICKY that does not guarantee that onStartCommand will be called again after being killed.

Int STOP_FOREGROUND_DETACH

Selector for stopForeground(int): if set, the notification previously supplied to #startForeground will be detached from the service's lifecycle. The notification will remain shown even after the service is stopped and destroyed.

Int STOP_FOREGROUND_LEGACY

Selector for stopForeground(int): equivalent to passing false to the legacy API stopForeground(boolean).

Int STOP_FOREGROUND_REMOVE

Selector for stopForeground(int): if supplied, the notification previously supplied to #startForeground will be cancelled and removed from display.

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 Unit

Attaches a android.view.SurfaceControl containing an accessibility overlay to the specified display.

Unit

Attaches a android.view.SurfaceControl containing an accessibility overlay to the specified display.

open Unit

Attaches an accessibility overlay android.view.SurfaceControl to the specified window.

Unit
attachAccessibilityOverlayToWindow(accessibilityWindowId: Int, sc: SurfaceControl, executor: Executor, callback: IntConsumer)

Attaches an accessibility overlay android.view.SurfaceControl to the specified window.

open Boolean

Clears the cache.

open Boolean

Invalidates node and its subtree in the cache.

open Context

Returns a new Context object from the current context but with resources adjusted to match the metrics of display.

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

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

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

Creates a Context for a non-activity window.

Unit

Disables the service.

Boolean

Dispatch a gesture to the touch screen.

open AccessibilityNodeInfo!
findFocus(focus: Int)

Find the view that has the specified focus type.

AccessibilityButtonController

Returns the controller for the accessibility button within the system's navigation area.

AccessibilityButtonController

Returns the controller of specified logical display for the accessibility button within the system's navigation area.

BrailleDisplayController

Returns the BrailleDisplayController which may be used to communicate with refreshable Braille displays that provide USB or Bluetooth Braille display HID support.

FingerprintGestureController

Get the controller for fingerprint gestures.

InputMethod?

Returns the InputMethod instance after the system calls onCreateInputMethod(), which may be used to input text or get editable text selection change notifications.

AccessibilityService.MagnificationController

Returns the magnification controller, which may be used to query and modify the state of display magnification.

open AccessibilityNodeInfo!

Gets the root node in the currently active window if this service can retrieve window content.

open AccessibilityNodeInfo?
getRootInActiveWindow(prefetchingStrategy: Int)

Gets the root node in the currently active window if this service can retrieve window content.

AccessibilityServiceInfo!

Gets the an AccessibilityServiceInfo describing this AccessibilityService.

AccessibilityService.SoftKeyboardController

Returns the soft keyboard controller, which may be used to query and modify the soft keyboard show mode.

MutableList<AccessibilityNodeInfo.AccessibilityAction!>

Returns a list of system actions available in the system right now.

open Any!

Return the handle to a system-level service by name.

TouchInteractionController

Returns the touch interaction controller for the specified logical display, which may be used to detect gestures and otherwise control touch interactions.

open MutableList<AccessibilityWindowInfo!>!

Gets the windows on the screen of the default display.

SparseArray<MutableList<AccessibilityWindowInfo!>!>

Gets the windows on the screen of all displays.

open Boolean

Returns true if the cache is enabled.

open Boolean

Checks if node is in the cache.

abstract Unit

Callback for android.view.accessibility.AccessibilityEvents.

IBinder?
onBind(intent: Intent!)

Implement to return the implementation of the internal accessibility service interface.

open InputMethod

The default implementation returns our default InputMethod.

open Boolean

Called by the system when the user performs a specific gesture on the specific touch screen.

abstract Unit

Callback for interrupting the accessibility feedback.

open Unit

Callback that allows an accessibility service to observe generic MotionEvents.

open Unit

This is called when the system action list is changed.

Boolean

Performs a global action.

open Unit
setAccessibilityFocusAppearance(strokeWidth: Int, color: Int)

Sets the strokeWidth and color of the accessibility focus rectangle.

open Unit

Sets the system settings values that control the scaling factor for animations.

open Boolean

Sets the cache status.

open Unit

When AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE is enabled, this function requests that touch interactions starting in the specified region of the screen bypass the gesture detector.

Unit

Sets the AccessibilityServiceInfo that describes this service.

open Unit

When AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE is enabled, this function requests that touch interactions starting in the specified region of the screen bypass the touch explorer and go straight to the view hierarchy.

open Unit

Takes a screenshot of the specified display and returns it via an AccessibilityService.ScreenshotResult.

open Unit
takeScreenshotOfWindow(accessibilityWindowId: Int, executor: Executor, callback: AccessibilityService.TakeScreenshotCallback)

Takes a screenshot of the specified window and returns it via an AccessibilityService.ScreenshotResult.

Protected methods
open Boolean
onGesture(gestureId: Int)

Called by onGesture(android.accessibilityservice.AccessibilityGestureEvent) when the user performs a specific gesture on the default display.

open Boolean

Callback that allows an accessibility service to observe the key events before they are passed to the rest of the system.

open Unit

This method is a part of the AccessibilityService lifecycle and is called after the system has successfully bound to the service.

Inherited functions
Unit attachBaseContext(newBase: Context!)

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

Print the Service's state into the given stream. This gets invoked if you run "adb shell dumpsys activity service <yourservicename>" (note that for this command to work, the service must be running, and you must specify a fully-qualified service name). This is distinct from "dumpsys <servicename>", which only works for named system services and which invokes the IBinder.dump method on the IBinder interface registered with ServiceManager.

Application! getApplication()

Return the application that owns this service.

Int getForegroundServiceType()

If the service has become a foreground service by calling startForeground(int,android.app.Notification) or startForeground(int,android.app.Notification,int), getForegroundServiceType() returns the current foreground service type.

If there is no foregroundServiceType specified in manifest, ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE is returned.

If the service is not a foreground service, ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE is returned.

Unit onConfigurationChanged(newConfig: Configuration)

Unit onCreate()

Called by the system when the service is first created. Do not call this method directly.

Unit onDestroy()

Called by the system to notify a Service that it is no longer used and is being removed. The service should clean up any resources it holds (threads, registered receivers, etc) at this point. Upon return, there will be no more calls in to this Service object and it is effectively dead. Do not call this method directly.

Unit onLowMemory()

Unit onRebind(intent: Intent!)

Called when new clients have connected to the service, after it had previously been notified that all had disconnected in its onUnbind. This will only be called if the implementation of onUnbind was overridden to return true.

Unit onStart(intent: Intent!, startId: Int)

Int onStartCommand(intent: Intent!, flags: Int, startId: Int)

Called by the system every time a client explicitly starts the service by calling android.content.Context#startService, providing the arguments it supplied and a unique integer token representing the start request. Do not call this method directly.

For backwards compatibility, the default implementation calls onStart and returns either START_STICKY or START_STICKY_COMPATIBILITY.

Note that the system calls this on your service's main thread. A service's main thread is the same thread where UI operations take place for Activities running in the same process. You should always avoid stalling the main thread's event loop. When doing long-running operations, network calls, or heavy disk I/O, you should kick off a new thread, or use android.os.AsyncTask.

Unit onTaskRemoved(rootIntent: Intent!)

This is called if the service is currently running and the user has removed a task that comes from the service's application. If you have set ServiceInfo.FLAG_STOP_WITH_TASK then you will not receive this callback; instead, the service will simply be stopped.

Unit onTimeout(startId: Int)

Callback called on timeout for ServiceInfo.FOREGROUND_SERVICE_TYPE_SHORT_SERVICE. See ServiceInfo.FOREGROUND_SERVICE_TYPE_SHORT_SERVICE for more details.

If the foreground service of type ServiceInfo.FOREGROUND_SERVICE_TYPE_SHORT_SERVICE doesn't finish even after it's timed out, the app will be declared an ANR after a short grace period of several seconds.

Starting from Android version android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM, onTimeout(int,int) will also be called when a foreground service of type ServiceInfo.FOREGROUND_SERVICE_TYPE_SHORT_SERVICE times out. Developers do not need to implement both of the callbacks on android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM and onwards.

Note, even though ServiceInfo.FOREGROUND_SERVICE_TYPE_SHORT_SERVICE was added on Android version android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE, it can be also used on on prior android versions (just like other new foreground service types can be used). However, because android.app.Service#onTimeout(int) did not exist on prior versions, it will never called on such versions. Because of this, developers must make sure to stop the foreground service even if android.app.Service#onTimeout(int) is not called on such versions.

Unit onTimeout(startId: Int, fgsType: Int)

Callback called when a particular foreground service type has timed out.

This callback is meant to give the app a small grace period of a few seconds to finish the foreground service of the associated type - if it fails to do so, the app will crash.

The foreground service of the associated type can be stopped within the time limit by android.app.Service#stopSelf(), android.content.Context#stopService(android.content.Intent) or their overloads. android.app.Service#stopForeground(int) can be used as well, which demotes the service to a "background" service, which will soon be stopped by the system.

The specific time limit for each type (if one exists) is mentioned in the documentation for that foreground service type. See dataSync for example.

Note: time limits are restricted to a rolling 24-hour window - for example, if a foreground service type has a time limit of 6 hours, that time counter begins as soon as the foreground service starts. This time limit will only be reset once every 24 hours or if the app comes into the foreground state.

Unit onTrimMemory(level: Int)

Boolean onUnbind(intent: Intent!)

Called when all clients have disconnected from a particular interface published by the service. The default implementation does nothing and returns false.

Unit startForeground(id: Int, notification: Notification!)

If your service is started (running through Context.startService(Intent)), then also make this service run in the foreground, supplying the ongoing notification to be shown to the user while in this state. By default started services are background, meaning that their process won't be given foreground CPU scheduling (unless something else in that process is foreground) and, if the system needs to kill them to reclaim more memory (such as to display a large page in a web browser), they can be killed without too much harm. You use #startForeground if killing your service would be disruptive to the user, such as if your service is performing background music playback, so the user would notice if their music stopped playing.

Note that calling this method does not put the service in the started state itself, even though the name sounds like it. You must always call startService(android.content.Intent) first to tell the system it should keep the service running, and then use this method to tell it to keep it running harder.

Apps targeting API android.os.Build.VERSION_CODES#P or later must request the permission android.Manifest.permission#FOREGROUND_SERVICE in order to use this API.

Apps built with SDK version android.os.Build.VERSION_CODES#Q or later can specify the foreground service types using attribute android.R.attr#foregroundServiceType in service element of manifest file. The value of attribute android.R.attr#foregroundServiceType can be multiple flags ORed together.

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.

Note: Beginning with SDK Version android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE, apps targeting SDK Version android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE or higher are not allowed to start foreground services without specifying a valid foreground service type in the manifest attribute android.R.attr#foregroundServiceType. See Behavior changes: Apps targeting Android 14 for more details.

Unit startForeground(id: Int, notification: Notification, foregroundServiceType: Int)

An overloaded version of startForeground(int,android.app.Notification) with additional foregroundServiceType parameter.

Apps built with SDK version android.os.Build.VERSION_CODES#Q or later can specify the foreground service types using attribute android.R.attr#foregroundServiceType in service element of manifest file. The value of attribute android.R.attr#foregroundServiceType can be multiple flags ORed together.

The foregroundServiceType parameter must be a subset flags of what is specified in manifest attribute android.R.attr#foregroundServiceType, if not, an IllegalArgumentException is thrown. Specify foregroundServiceType parameter as android.content.pm.ServiceInfo#FOREGROUND_SERVICE_TYPE_MANIFEST to use all flags that is specified in manifest attribute foregroundServiceType.

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.

Note: Beginning with SDK Version android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE, apps targeting SDK Version android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE or higher are not allowed to start foreground services without specifying a valid foreground service type in the manifest attribute android.R.attr#foregroundServiceType, and the parameter foregroundServiceType here must not be the ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE. See Behavior changes: Apps targeting Android 14 for more details.

Unit stopForeground(removeNotification: Boolean)

Legacy version of stopForeground(int).

Unit stopForeground(notificationBehavior: Int)

Remove this service from foreground state, allowing it to be killed if more memory is needed. This does not stop the service from running (for that you use stopSelf() or related methods), just takes it out of the foreground state.

If STOP_FOREGROUND_REMOVE is supplied, the service's associated notification will be cancelled immediately.

If STOP_FOREGROUND_DETACH is supplied, the service's association with the notification will be severed. If the notification had not yet been shown, due to foreground-service notification deferral policy, it is immediately posted when stopForeground(STOP_FOREGROUND_DETACH) is called. In all cases, the notification remains shown even after this service is stopped fully and destroyed.

If zero is passed as the argument, the result will be the legacy behavior as defined prior to Android L: the notification will remain posted until the service is fully stopped, at which time it will automatically be cancelled.

Unit stopSelf()

Stop the service, if it was previously started. This is the same as calling android.content.Context#stopService for this particular service.

Unit stopSelf(startId: Int)

Old version of stopSelfResult that doesn't return a result.

Boolean stopSelfResult(startId: Int)

Stop the service if the most recent time it was started was startId. This is the same as calling android.content.Context#stopService for this particular service but allows you to safely avoid stopping if there is a start request from a client that you haven't yet seen in onStart.

Be careful about ordering of your calls to this function.. If you call this function with the most-recently received ID before you have called it for previously received IDs, the service will be immediately stopped anyway. If you may end up processing IDs out of order (such as by dispatching them on separate threads), then you are responsible for stopping them in the same order you received them.

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

AssetManager! getAssets()

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

Resources! getResources()

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

Any! getSystemService(name: String)

String? getSystemServiceName(serviceClass: Class<*>)

Resources.Theme! getTheme()

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 setTheme(resid: Int)

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.

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.

Constants

ERROR_TAKE_SCREENSHOT_INTERNAL_ERROR

Added in API level 30
static val ERROR_TAKE_SCREENSHOT_INTERNAL_ERROR: Int

The status of taking screenshot is failure and the reason is internal error.

Value: 1

ERROR_TAKE_SCREENSHOT_INTERVAL_TIME_SHORT

Added in API level 30
static val ERROR_TAKE_SCREENSHOT_INTERVAL_TIME_SHORT: Int

The status of taking screenshot is failure and the reason is that too little time has elapsed since the last screenshot.

Value: 3

ERROR_TAKE_SCREENSHOT_INVALID_DISPLAY

Added in API level 30
static val ERROR_TAKE_SCREENSHOT_INVALID_DISPLAY: Int

The status of taking screenshot is failure and the reason is invalid display Id.

Value: 4

ERROR_TAKE_SCREENSHOT_INVALID_WINDOW

Added in API level 34
static val ERROR_TAKE_SCREENSHOT_INVALID_WINDOW: Int

The status of taking screenshot is failure and the reason is invalid accessibility window Id.

Value: 5

ERROR_TAKE_SCREENSHOT_NO_ACCESSIBILITY_ACCESS

Added in API level 30
static val ERROR_TAKE_SCREENSHOT_NO_ACCESSIBILITY_ACCESS: Int

The status of taking screenshot is failure and the reason is no accessibility access.

Value: 2

ERROR_TAKE_SCREENSHOT_SECURE_WINDOW

Added in API level 34
static val ERROR_TAKE_SCREENSHOT_SECURE_WINDOW: Int

The status of taking screenshot is failure and the reason is the window contains secure content.

Value: 6

GESTURE_2_FINGER_DOUBLE_TAP

Added in API level 30
static val GESTURE_2_FINGER_DOUBLE_TAP: Int

The user has performed a two-finger double tap gesture on the touch screen.

Value: 20

GESTURE_2_FINGER_DOUBLE_TAP_AND_HOLD

Added in API level 30
static val GESTURE_2_FINGER_DOUBLE_TAP_AND_HOLD: Int

The user has performed a two-finger double tap and hold gesture on the touch screen.

Value: 40

GESTURE_2_FINGER_SINGLE_TAP

Added in API level 30
static val GESTURE_2_FINGER_SINGLE_TAP: Int

The user has performed a two-finger single tap gesture on the touch screen.

Value: 19

GESTURE_2_FINGER_SWIPE_DOWN

Added in API level 30
static val GESTURE_2_FINGER_SWIPE_DOWN: Int

The user has performed a two-finger swipe down gesture on the touch screen.

Value: 26

GESTURE_2_FINGER_SWIPE_LEFT

Added in API level 30
static val GESTURE_2_FINGER_SWIPE_LEFT: Int

The user has performed a two-finger swipe left gesture on the touch screen.

Value: 27

GESTURE_2_FINGER_SWIPE_RIGHT

Added in API level 30
static val GESTURE_2_FINGER_SWIPE_RIGHT: Int

The user has performed a two-finger swipe right gesture on the touch screen.

Value: 28

GESTURE_2_FINGER_SWIPE_UP

Added in API level 30
static val GESTURE_2_FINGER_SWIPE_UP: Int

The user has performed a two-finger swipe up gesture on the touch screen.

Value: 25

GESTURE_2_FINGER_TRIPLE_TAP

Added in API level 30
static val GESTURE_2_FINGER_TRIPLE_TAP: Int

The user has performed a two-finger triple tap gesture on the touch screen.

Value: 21

GESTURE_2_FINGER_TRIPLE_TAP_AND_HOLD

Added in API level 31
static val GESTURE_2_FINGER_TRIPLE_TAP_AND_HOLD: Int

The user has performed a two-finger triple-tap and hold gesture on the touch screen.

Value: 43

GESTURE_3_FINGER_DOUBLE_TAP

Added in API level 30
static val GESTURE_3_FINGER_DOUBLE_TAP: Int

The user has performed a three-finger double tap gesture on the touch screen.

Value: 23

GESTURE_3_FINGER_DOUBLE_TAP_AND_HOLD

Added in API level 30
static val GESTURE_3_FINGER_DOUBLE_TAP_AND_HOLD: Int

The user has performed a three-finger double tap and hold gesture on the touch screen.

Value: 41

GESTURE_3_FINGER_SINGLE_TAP

Added in API level 30
static val GESTURE_3_FINGER_SINGLE_TAP: Int

The user has performed a three-finger single tap gesture on the touch screen.

Value: 22

GESTURE_3_FINGER_SINGLE_TAP_AND_HOLD

Added in API level 31
static val GESTURE_3_FINGER_SINGLE_TAP_AND_HOLD: Int

The user has performed a three-finger single-tap and hold gesture on the touch screen.

Value: 44

GESTURE_3_FINGER_SWIPE_DOWN

Added in API level 30
static val GESTURE_3_FINGER_SWIPE_DOWN: Int

The user has performed a three-finger swipe down gesture on the touch screen.

Value: 30

GESTURE_3_FINGER_SWIPE_LEFT

Added in API level 30
static val GESTURE_3_FINGER_SWIPE_LEFT: Int

The user has performed a three-finger swipe left gesture on the touch screen.

Value: 31

GESTURE_3_FINGER_SWIPE_RIGHT

Added in API level 30
static val GESTURE_3_FINGER_SWIPE_RIGHT: Int

The user has performed a three-finger swipe right gesture on the touch screen.

Value: 32

GESTURE_3_FINGER_SWIPE_UP

Added in API level 30
static val GESTURE_3_FINGER_SWIPE_UP: Int

The user has performed a three-finger swipe up gesture on the touch screen.

Value: 29

GESTURE_3_FINGER_TRIPLE_TAP

Added in API level 30
static val GESTURE_3_FINGER_TRIPLE_TAP: Int

The user has performed a three-finger triple tap gesture on the touch screen.

Value: 24

GESTURE_3_FINGER_TRIPLE_TAP_AND_HOLD

Added in API level 31
static val GESTURE_3_FINGER_TRIPLE_TAP_AND_HOLD: Int

The user has performed a three-finger triple-tap and hold gesture on the touch screen.

Value: 45

GESTURE_4_FINGER_DOUBLE_TAP

Added in API level 30
static val GESTURE_4_FINGER_DOUBLE_TAP: Int

The user has performed a four-finger double tap gesture on the touch screen.

Value: 38

GESTURE_4_FINGER_DOUBLE_TAP_AND_HOLD

Added in API level 30
static val GESTURE_4_FINGER_DOUBLE_TAP_AND_HOLD: Int

The user has performed a two-finger double tap and hold gesture on the touch screen.

Value: 42

GESTURE_4_FINGER_SINGLE_TAP

Added in API level 30
static val GESTURE_4_FINGER_SINGLE_TAP: Int

The user has performed a four-finger single tap gesture on the touch screen.

Value: 37

GESTURE_4_FINGER_SWIPE_DOWN

Added in API level 30
static val GESTURE_4_FINGER_SWIPE_DOWN: Int

The user has performed a four-finger swipe down gesture on the touch screen.

Value: 34

GESTURE_4_FINGER_SWIPE_LEFT

Added in API level 30
static val GESTURE_4_FINGER_SWIPE_LEFT: Int

The user has performed a four-finger swipe left gesture on the touch screen.

Value: 35

GESTURE_4_FINGER_SWIPE_RIGHT

Added in API level 30
static val GESTURE_4_FINGER_SWIPE_RIGHT: Int

The user has performed a four-finger swipe right gesture on the touch screen.

Value: 36

GESTURE_4_FINGER_SWIPE_UP

Added in API level 30
static val GESTURE_4_FINGER_SWIPE_UP: Int

The user has performed a four-finger swipe up gesture on the touch screen.

Value: 33

GESTURE_4_FINGER_TRIPLE_TAP

Added in API level 30
static val GESTURE_4_FINGER_TRIPLE_TAP: Int

The user has performed a four-finger triple tap gesture on the touch screen.

Value: 39

GESTURE_DOUBLE_TAP

Added in API level 30
static val GESTURE_DOUBLE_TAP: Int

The user has performed a double tap gesture on the touch screen.

Value: 17

GESTURE_DOUBLE_TAP_AND_HOLD

Added in API level 30
static val GESTURE_DOUBLE_TAP_AND_HOLD: Int

The user has performed a double tap and hold gesture on the touch screen.

Value: 18

GESTURE_SWIPE_DOWN

Added in API level 16
static val GESTURE_SWIPE_DOWN: Int

The user has performed a swipe down gesture on the touch screen.

Value: 2

GESTURE_SWIPE_DOWN_AND_LEFT

Added in API level 16
static val GESTURE_SWIPE_DOWN_AND_LEFT: Int

The user has performed a down and left gesture on the touch screen.

Value: 15

GESTURE_SWIPE_DOWN_AND_RIGHT

Added in API level 16
static val GESTURE_SWIPE_DOWN_AND_RIGHT: Int

The user has performed a down and right gesture on the touch screen.

Value: 16

GESTURE_SWIPE_DOWN_AND_UP

Added in API level 16
static val GESTURE_SWIPE_DOWN_AND_UP: Int

The user has performed a swipe down and up gesture on the touch screen.

Value: 8

GESTURE_SWIPE_LEFT

Added in API level 16
static val GESTURE_SWIPE_LEFT: Int

The user has performed a swipe left gesture on the touch screen.

Value: 3

GESTURE_SWIPE_LEFT_AND_DOWN

Added in API level 16
static val GESTURE_SWIPE_LEFT_AND_DOWN: Int

The user has performed a left and down gesture on the touch screen.

Value: 10

GESTURE_SWIPE_LEFT_AND_RIGHT

Added in API level 16
static val GESTURE_SWIPE_LEFT_AND_RIGHT: Int

The user has performed a swipe left and right gesture on the touch screen.

Value: 5

GESTURE_SWIPE_LEFT_AND_UP

Added in API level 16
static val GESTURE_SWIPE_LEFT_AND_UP: Int

The user has performed a left and up gesture on the touch screen.

Value: 9

GESTURE_SWIPE_RIGHT

Added in API level 16
static val GESTURE_SWIPE_RIGHT: Int

The user has performed a swipe right gesture on the touch screen.

Value: 4

GESTURE_SWIPE_RIGHT_AND_DOWN

Added in API level 16
static val GESTURE_SWIPE_RIGHT_AND_DOWN: Int

The user has performed a right and down gesture on the touch screen.

Value: 12

GESTURE_SWIPE_RIGHT_AND_LEFT

Added in API level 16
static val GESTURE_SWIPE_RIGHT_AND_LEFT: Int

The user has performed a swipe right and left gesture on the touch screen.

Value: 6

GESTURE_SWIPE_RIGHT_AND_UP

Added in API level 16
static val GESTURE_SWIPE_RIGHT_AND_UP: Int

The user has performed a right and up gesture on the touch screen.

Value: 11

GESTURE_SWIPE_UP

Added in API level 16
static val GESTURE_SWIPE_UP: Int

The user has performed a swipe up gesture on the touch screen.

Value: 1

GESTURE_SWIPE_UP_AND_DOWN

Added in API level 16
static val GESTURE_SWIPE_UP_AND_DOWN: Int

The user has performed a swipe up and down gesture on the touch screen.

Value: 7

GESTURE_SWIPE_UP_AND_LEFT

Added in API level 16
static val GESTURE_SWIPE_UP_AND_LEFT: Int

The user has performed an up and left gesture on the touch screen.

Value: 13

GESTURE_SWIPE_UP_AND_RIGHT

Added in API level 16
static val GESTURE_SWIPE_UP_AND_RIGHT: Int

The user has performed an up and right gesture on the touch screen.

Value: 14

GESTURE_UNKNOWN

Added in API level 31
static val GESTURE_UNKNOWN: Int

The user has performed an unrecognized gesture on the touch screen. This gesture is only dispatched when AccessibilityServiceInfo.FLAG_SEND_MOTION_EVENTS is set.

Value: 0

GLOBAL_ACTION_ACCESSIBILITY_ALL_APPS

Added in API level 31
static val GLOBAL_ACTION_ACCESSIBILITY_ALL_APPS: Int

Action to show Launcher's all apps.

Value: 14

GLOBAL_ACTION_ACCESSIBILITY_BUTTON

Added in API level 31
static val GLOBAL_ACTION_ACCESSIBILITY_BUTTON: Int

Action to trigger the Accessibility Button

Value: 11

GLOBAL_ACTION_ACCESSIBILITY_BUTTON_CHOOSER

Added in API level 31
static val GLOBAL_ACTION_ACCESSIBILITY_BUTTON_CHOOSER: Int

Action to bring up the Accessibility Button's chooser menu

Value: 12

GLOBAL_ACTION_ACCESSIBILITY_SHORTCUT

Added in API level 31
static val GLOBAL_ACTION_ACCESSIBILITY_SHORTCUT: Int

Action to trigger the Accessibility Shortcut. This shortcut has a hardware trigger and can be activated by holding down the two volume keys.

Value: 13

GLOBAL_ACTION_BACK

Added in API level 16
static val GLOBAL_ACTION_BACK: Int

Action to go back.

Value: 1

GLOBAL_ACTION_DISMISS_NOTIFICATION_SHADE

Added in API level 31
static val GLOBAL_ACTION_DISMISS_NOTIFICATION_SHADE: Int

Action to dismiss the notification shade

Value: 15

GLOBAL_ACTION_DPAD_CENTER

Added in API level 33
static val GLOBAL_ACTION_DPAD_CENTER: Int

Action to trigger dpad center keyevent.

Value: 20

GLOBAL_ACTION_DPAD_DOWN

Added in API level 33
static val GLOBAL_ACTION_DPAD_DOWN: Int

Action to trigger dpad down keyevent.

Value: 17

GLOBAL_ACTION_DPAD_LEFT

Added in API level 33
static val GLOBAL_ACTION_DPAD_LEFT: Int

Action to trigger dpad left keyevent.

Value: 18

GLOBAL_ACTION_DPAD_RIGHT

Added in API level 33
static val GLOBAL_ACTION_DPAD_RIGHT: Int

Action to trigger dpad right keyevent.

Value: 19

GLOBAL_ACTION_DPAD_UP

Added in API level 33
static val GLOBAL_ACTION_DPAD_UP: Int

Action to trigger dpad up keyevent.

Value: 16

GLOBAL_ACTION_HOME

Added in API level 16
static val GLOBAL_ACTION_HOME: Int

Action to go home.

Value: 2

GLOBAL_ACTION_KEYCODE_HEADSETHOOK

Added in API level 31
static val GLOBAL_ACTION_KEYCODE_HEADSETHOOK: Int

Action to send the KEYCODE_HEADSETHOOK KeyEvent, which is used to answer and hang up calls and play and stop media. Calling takes priority. If there is an incoming call, this action can be used to answer that call, and if there is an ongoing call, to hang up on that call.

Value: 10

GLOBAL_ACTION_LOCK_SCREEN

Added in API level 28
static val GLOBAL_ACTION_LOCK_SCREEN: Int

Action to lock the screen

Value: 8

GLOBAL_ACTION_MEDIA_PLAY_PAUSE

static val GLOBAL_ACTION_MEDIA_PLAY_PAUSE: Int

Action to trigger media play/pause key event.

Value: 22

GLOBAL_ACTION_MENU

static val GLOBAL_ACTION_MENU: Int

Action to trigger menu key event.

Value: 21

GLOBAL_ACTION_NOTIFICATIONS

Added in API level 16
static val GLOBAL_ACTION_NOTIFICATIONS: Int

Action to open the notifications.

Value: 4

GLOBAL_ACTION_POWER_DIALOG

Added in API level 21
static val GLOBAL_ACTION_POWER_DIALOG: Int

Action to open the power long-press dialog.

Value: 6

GLOBAL_ACTION_QUICK_SETTINGS

Added in API level 17
static val GLOBAL_ACTION_QUICK_SETTINGS: Int

Action to open the quick settings.

Value: 5

GLOBAL_ACTION_RECENTS

Added in API level 16
static val GLOBAL_ACTION_RECENTS: Int

Action to toggle showing the overview of recent apps. Will fail on platforms that don't show recent apps.

Value: 3

GLOBAL_ACTION_TAKE_SCREENSHOT

Added in API level 28
static val GLOBAL_ACTION_TAKE_SCREENSHOT: Int

Action to take a screenshot

Value: 9

GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN

Added in API level 24
static val GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN: Int

Action to toggle docking the current app's window.

Note: It is effective only if it appears in getSystemActions().

Value: 7

OVERLAY_RESULT_INTERNAL_ERROR

static val OVERLAY_RESULT_INTERNAL_ERROR: Int

Result code indicating the overlay could not be attached due to an internal error and not because of problems with the input.

Value: 1

OVERLAY_RESULT_INVALID

static val OVERLAY_RESULT_INVALID: Int

Result code indicating the overlay could not be attached because the specified display or window id was invalid.

Value: 2

OVERLAY_RESULT_SUCCESS

static val OVERLAY_RESULT_SUCCESS: Int

Result code indicating the overlay was successfully attached.

Value: 0

SERVICE_INTERFACE

Added in API level 4
static val SERVICE_INTERFACE: String

The Intent that must be declared as handled by the service.

Value: "android.accessibilityservice.AccessibilityService"

SERVICE_META_DATA

Added in API level 14
static val SERVICE_META_DATA: String

Name under which an AccessibilityService component publishes information about itself. This meta-data must reference an XML resource containing an <accessibility-service> tag. This is a sample XML file configuring an accessibility service:

<accessibility-service
      android:accessibilityEventTypes="typeViewClicked|typeViewFocused"
      android:packageNames="foo.bar, foo.baz"
      android:accessibilityFeedbackType="feedbackSpoken"
      android:notificationTimeout="100"
      android:accessibilityFlags="flagDefault"
      android:settingsActivity="foo.bar.TestBackActivity"
      android:canRetrieveWindowContent="true"
      android:canRequestTouchExplorationMode="true"
      . . .
  />

Value: "android.accessibilityservice"

SHOW_MODE_AUTO

Added in API level 24
static val SHOW_MODE_AUTO: Int

Allow the system to control when the soft keyboard is shown.

Value: 0

SHOW_MODE_HIDDEN

Added in API level 24
static val SHOW_MODE_HIDDEN: Int

Never show the soft keyboard.

Value: 1

SHOW_MODE_IGNORE_HARD_KEYBOARD

Added in API level 29
static val SHOW_MODE_IGNORE_HARD_KEYBOARD: Int

Allow the soft keyboard to be shown, even if a hard keyboard is connected

Value: 2

Public constructors

AccessibilityService

AccessibilityService()

Public methods

attachAccessibilityOverlayToDisplay

Added in API level 34
open fun attachAccessibilityOverlayToDisplay(
    displayId: Int,
    sc: SurfaceControl
): Unit

Attaches a android.view.SurfaceControl containing an accessibility overlay to the specified display. This type of overlay should be used for content that does not need to track the location and size of Views in the currently active app e.g. service configuration or general service UI.

Generally speaking, an accessibility overlay will be a android.view.View. To embed the View into a android.view.SurfaceControl, create a and attach the View using android.view.SurfaceControlViewHost#setView. Then obtain the SurfaceControl by calling viewHost.getSurfacePackage().getSurfaceControl().

To remove this overlay and free the associated resources, use new SurfaceControl.Transaction().reparent(sc, null).apply();.

If the specified overlay has already been attached to the specified display this method does nothing. If the specified overlay has already been attached to a previous display this function will transfer the overlay to the new display. Services can attach multiple overlays. Use new SurfaceControl.Transaction().setLayer(sc, layer).apply();. to coordinate the order of the overlays on screen.

Parameters
displayId Int: the display to which the SurfaceControl should be attached.
sc SurfaceControl: the SurfaceControl containing the overlay content This value cannot be null.

attachAccessibilityOverlayToDisplay

fun attachAccessibilityOverlayToDisplay(
    displayId: Int,
    sc: SurfaceControl,
    executor: Executor,
    callback: IntConsumer
): Unit

Attaches a android.view.SurfaceControl containing an accessibility overlay to the specified display. This type of overlay should be used for content that does not need to track the location and size of Views in the currently active app e.g. service configuration or general service UI.

Generally speaking, an accessibility overlay will be a android.view.View. To embed the View into a android.view.SurfaceControl, create a and attach the View using android.view.SurfaceControlViewHost#setView. Then obtain the SurfaceControl by calling viewHost.getSurfacePackage().getSurfaceControl().

To remove this overlay and free the associated resources, use new SurfaceControl.Transaction().reparent(sc, null).apply();.

If the specified overlay has already been attached to the specified display this method does nothing. If the specified overlay has already been attached to a previous display this function will transfer the overlay to the new display. Services can attach multiple overlays. Use new SurfaceControl.Transaction().setLayer(sc, layer).apply();. to coordinate the order of the overlays on screen.

Parameters
displayId Int: the display to which the SurfaceControl should be attached.
sc SurfaceControl: the SurfaceControl containing the overlay content This value cannot be null.
executor Executor: Executor on which to run the callback. This value cannot be null. Callback and listener events are dispatched through this Executor, providing an easy way to control which thread is used. To dispatch events through the main thread of your application, you can use Context.getMainExecutor(). Otherwise, provide an Executor that dispatches to an appropriate thread.
callback IntConsumer: The callback invoked when attaching the overlay has succeeded or failed. The callback is a java.util.function.IntConsumer of the result status code. This value cannot be null.

attachAccessibilityOverlayToWindow

Added in API level 34
open fun attachAccessibilityOverlayToWindow(
    accessibilityWindowId: Int,
    sc: SurfaceControl
): Unit

Attaches an accessibility overlay android.view.SurfaceControl to the specified window. This method should be used when you want the overlay to move and resize as the parent window moves and resizes.

Generally speaking, an accessibility overlay will be a android.view.View. To embed the View into a android.view.SurfaceControl, create a and attach the View using android.view.SurfaceControlViewHost#setView. Then obtain the SurfaceControl by calling viewHost.getSurfacePackage().getSurfaceControl().

To remove this overlay and free the associated resources, use new SurfaceControl.Transaction().reparent(sc, null).apply();.

If the specified overlay has already been attached to the specified window this method does nothing. If the specified overlay has already been attached to a previous window this function will transfer the overlay to the new window. Services can attach multiple overlays. Use new SurfaceControl.Transaction().setLayer(sc, layer).apply();. to coordinate the order of the overlays on screen.

Parameters
accessibilityWindowId Int: The window id, from AccessibilityWindowInfo.getId().
sc SurfaceControl: the SurfaceControl containing the overlay content This value cannot be null.

attachAccessibilityOverlayToWindow

fun attachAccessibilityOverlayToWindow(
    accessibilityWindowId: Int,
    sc: SurfaceControl,
    executor: Executor,
    callback: IntConsumer
): Unit

Attaches an accessibility overlay android.view.SurfaceControl to the specified window. This method should be used when you want the overlay to move and resize as the parent window moves and resizes.

Generally speaking, an accessibility overlay will be a android.view.View. To embed the View into a android.view.SurfaceControl, create a and attach the View using android.view.SurfaceControlViewHost#setView. Then obtain the SurfaceControl by calling viewHost.getSurfacePackage().getSurfaceControl().

To remove this overlay and free the associated resources, use new SurfaceControl.Transaction().reparent(sc, null).apply();.

If the specified overlay has already been attached to the specified window this method does nothing. If the specified overlay has already been attached to a previous window this function will transfer the overlay to the new window. Services can attach multiple overlays. Use new SurfaceControl.Transaction().setLayer(sc, layer).apply();. to coordinate the order of the overlays on screen.

Parameters
accessibilityWindowId Int: The window id, from AccessibilityWindowInfo.getId().
sc SurfaceControl: the SurfaceControl containing the overlay content This value cannot be null.
executor Executor: Executor on which to run the callback. This value cannot be null. Callback and listener events are dispatched through this Executor, providing an easy way to control which thread is used. To dispatch events through the main thread of your application, you can use Context.getMainExecutor(). Otherwise, provide an Executor that dispatches to an appropriate thread.
callback IntConsumer: The callback invoked when attaching the overlay has succeeded or failed. The callback is a java.util.function.IntConsumer of the result status code. This value cannot be null.

clearCache

Added in API level 33
open fun clearCache(): Boolean

Clears the cache.

Return
Boolean true if the cache was cleared

clearCachedSubtree

Added in API level 33
open fun clearCachedSubtree(node: AccessibilityNodeInfo): Boolean

Invalidates node and its subtree in the cache.

Parameters
node AccessibilityNodeInfo: the node to invalidate. This value cannot be null.
Return
Boolean true if the subtree rooted at node was invalidated.

createDisplayContext

Added in API level 17
open fun createDisplayContext(display: Display): Context

Returns a new Context object from the current context but with resources adjusted to match the metrics of display. 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.

Note: This Context is not expected to be updated with new configuration if the underlying display configuration changes and the cached Resources it returns could be stale. It is suggested to use android.hardware.display.DisplayManager.DisplayListener to listen for changes and re-create an instance if necessary.

This Context is not a UI context, do not use it to access UI components or obtain a WindowManager instance.

To obtain an instance of WindowManager configured to show windows on the given display, call createWindowContext(int,android.os.Bundle) on the returned display context, then call getSystemService(java.lang.String) or getSystemService(java.lang.Class) on the returned window context.

Parameters
display Display: The display to which the current context's resources are adjusted. This value cannot be null.
Return
Context This value cannot be null.

createWindowContext

Added in API level 31
open fun createWindowContext(
    display: Display,
    type: Int,
    options: Bundle?
): Context

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.

Parameters
display Display: This value cannot be null.
type Int: Value is android.view.WindowManager.LayoutParams#TYPE_BASE_APPLICATION, android.view.WindowManager.LayoutParams#TYPE_APPLICATION, android.view.WindowManager.LayoutParams#TYPE_APPLICATION_STARTING, android.view.WindowManager.LayoutParams#TYPE_DRAWN_APPLICATION, android.view.WindowManager.LayoutParams#TYPE_APPLICATION_PANEL, android.view.WindowManager.LayoutParams#TYPE_APPLICATION_MEDIA, android.view.WindowManager.LayoutParams#TYPE_APPLICATION_SUB_PANEL, android.view.WindowManager.LayoutParams#TYPE_APPLICATION_ATTACHED_DIALOG, android.view.WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA_OVERLAY, android.view.WindowManager.LayoutParams.TYPE_APPLICATION_ABOVE_SUB_PANEL, android.view.WindowManager.LayoutParams#TYPE_STATUS_BAR, android.view.WindowManager.LayoutParams#TYPE_SEARCH_BAR, android.view.WindowManager.LayoutParams#TYPE_PHONE, android.view.WindowManager.LayoutParams#TYPE_SYSTEM_ALERT, android.view.WindowManager.LayoutParams.TYPE_KEYGUARD, android.view.WindowManager.LayoutParams#TYPE_TOAST, android.view.WindowManager.LayoutParams#TYPE_SYSTEM_OVERLAY, android.view.WindowManager.LayoutParams#TYPE_PRIORITY_PHONE, android.view.WindowManager.LayoutParams#TYPE_SYSTEM_DIALOG, android.view.WindowManager.LayoutParams#TYPE_KEYGUARD_DIALOG, android.view.WindowManager.LayoutParams#TYPE_SYSTEM_ERROR, android.view.WindowManager.LayoutParams#TYPE_INPUT_METHOD, android.view.WindowManager.LayoutParams#TYPE_INPUT_METHOD_DIALOG, android.view.WindowManager.LayoutParams#TYPE_WALLPAPER, android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL, android.view.WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY, android.view.WindowManager.LayoutParams.TYPE_DRAG, android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_SUB_PANEL, android.view.WindowManager.LayoutParams.TYPE_POINTER, android.view.WindowManager.LayoutParams.TYPE_NAVIGATION_BAR, android.view.WindowManager.LayoutParams.TYPE_VOLUME_OVERLAY, android.view.WindowManager.LayoutParams.TYPE_BOOT_PROGRESS, android.view.WindowManager.LayoutParams.TYPE_INPUT_CONSUMER, android.view.WindowManager.LayoutParams.TYPE_NAVIGATION_BAR_PANEL, android.view.WindowManager.LayoutParams.TYPE_DISPLAY_OVERLAY, android.view.WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY, android.view.WindowManager.LayoutParams#TYPE_PRIVATE_PRESENTATION, android.view.WindowManager.LayoutParams.TYPE_VOICE_INTERACTION, android.view.WindowManager.LayoutParams#TYPE_ACCESSIBILITY_OVERLAY, android.view.WindowManager.LayoutParams.TYPE_VOICE_INTERACTION_STARTING, android.view.WindowManager.LayoutParams.TYPE_DOCK_DIVIDER, android.view.WindowManager.LayoutParams.TYPE_QS_DIALOG, android.view.WindowManager.LayoutParams.TYPE_SCREENSHOT, android.view.WindowManager.LayoutParams.TYPE_PRESENTATION, android.view.WindowManager.LayoutParams#TYPE_APPLICATION_OVERLAY, android.view.WindowManager.LayoutParams.TYPE_ACCESSIBILITY_MAGNIFICATION_OVERLAY, android.view.WindowManager.LayoutParams.TYPE_NOTIFICATION_SHADE, or android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_ADDITIONAL
options Bundle?: This value may be null.
Return
Context This value cannot be null.
Exceptions
java.lang.IllegalArgumentException if the Display is null.

createWindowContext

Added in API level 30
open fun createWindowContext(
    type: Int,
    options: Bundle?
): Context

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.

Parameters
type Int: Value is android.view.WindowManager.LayoutParams#TYPE_BASE_APPLICATION, android.view.WindowManager.LayoutParams#TYPE_APPLICATION, android.view.WindowManager.LayoutParams#TYPE_APPLICATION_STARTING, android.view.WindowManager.LayoutParams#TYPE_DRAWN_APPLICATION, android.view.WindowManager.LayoutParams#TYPE_APPLICATION_PANEL, android.view.WindowManager.LayoutParams#TYPE_APPLICATION_MEDIA, android.view.WindowManager.LayoutParams#TYPE_APPLICATION_SUB_PANEL, android.view.WindowManager.LayoutParams#TYPE_APPLICATION_ATTACHED_DIALOG, android.view.WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA_OVERLAY, android.view.WindowManager.LayoutParams.TYPE_APPLICATION_ABOVE_SUB_PANEL, android.view.WindowManager.LayoutParams#TYPE_STATUS_BAR, android.view.WindowManager.LayoutParams#TYPE_SEARCH_BAR, android.view.WindowManager.LayoutParams#TYPE_PHONE, android.view.WindowManager.LayoutParams#TYPE_SYSTEM_ALERT, android.view.WindowManager.LayoutParams.TYPE_KEYGUARD, android.view.WindowManager.LayoutParams#TYPE_TOAST, android.view.WindowManager.LayoutParams#TYPE_SYSTEM_OVERLAY, android.view.WindowManager.LayoutParams#TYPE_PRIORITY_PHONE, android.view.WindowManager.LayoutParams#TYPE_SYSTEM_DIALOG, android.view.WindowManager.LayoutParams#TYPE_KEYGUARD_DIALOG, android.view.WindowManager.LayoutParams#TYPE_SYSTEM_ERROR, android.view.WindowManager.LayoutParams#TYPE_INPUT_METHOD, android.view.WindowManager.LayoutParams#TYPE_INPUT_METHOD_DIALOG, android.view.WindowManager.LayoutParams#TYPE_WALLPAPER, android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL, android.view.WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY, android.view.WindowManager.LayoutParams.TYPE_DRAG, android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_SUB_PANEL, android.view.WindowManager.LayoutParams.TYPE_POINTER, android.view.WindowManager.LayoutParams.TYPE_NAVIGATION_BAR, android.view.WindowManager.LayoutParams.TYPE_VOLUME_OVERLAY, android.view.WindowManager.LayoutParams.TYPE_BOOT_PROGRESS, android.view.WindowManager.LayoutParams.TYPE_INPUT_CONSUMER, android.view.WindowManager.LayoutParams.TYPE_NAVIGATION_BAR_PANEL, android.view.WindowManager.LayoutParams.TYPE_DISPLAY_OVERLAY, android.view.WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY, android.view.WindowManager.LayoutParams#TYPE_PRIVATE_PRESENTATION, android.view.WindowManager.LayoutParams.TYPE_VOICE_INTERACTION, android.view.WindowManager.LayoutParams#TYPE_ACCESSIBILITY_OVERLAY, android.view.WindowManager.LayoutParams.TYPE_VOICE_INTERACTION_STARTING, android.view.WindowManager.LayoutParams.TYPE_DOCK_DIVIDER, android.view.WindowManager.LayoutParams.TYPE_QS_DIALOG, android.view.WindowManager.LayoutParams.TYPE_SCREENSHOT, android.view.WindowManager.LayoutParams.TYPE_PRESENTATION, android.view.WindowManager.LayoutParams#TYPE_APPLICATION_OVERLAY, android.view.WindowManager.LayoutParams.TYPE_ACCESSIBILITY_MAGNIFICATION_OVERLAY, android.view.WindowManager.LayoutParams.TYPE_NOTIFICATION_SHADE, or android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_ADDITIONAL
options Bundle?: This value may be null.
Return
Context This value cannot be null.
Exceptions
java.lang.UnsupportedOperationException if this Context does not attach to a display, such as Application or Service.

disableSelf

Added in API level 24
fun disableSelf(): Unit

Disables the service. After calling this method, the service will be disabled and settings will show that it is turned off.

dispatchGesture

Added in API level 24
fun dispatchGesture(
    gesture: GestureDescription,
    callback: AccessibilityService.GestureResultCallback?,
    handler: Handler?
): Boolean

Dispatch a gesture to the touch screen. Any gestures currently in progress, whether from the user, this service, or another service, will be cancelled.

The gesture will be dispatched as if it were performed directly on the screen by a user, so the events may be affected by features such as magnification and explore by touch.

Note: In order to dispatch gestures, your service must declare the capability by setting the android.R.styleable#AccessibilityService_canPerformGestures property in its meta-data. For more information, see SERVICE_META_DATA.

Since many apps do not appropriately support AccessibilityAction.ACTION_CLICK, if this action fails on an element that should be clickable, a service that is not a screen reader may send a tap directly to the element as a fallback. The example below demonstrates this fallback using the gesture dispatch APIs:

<code>
      private void tap(PointF point) {
          StrokeDescription tap =  new StrokeDescription(path(point), 0,
          ViewConfiguration.getTapTimeout());
          GestureDescription.Builder builder = new GestureDescription.Builder();
          builder.addStroke(tap);
          dispatchGesture(builder.build(), null, null);
      }
 </code>
Parameters
gesture GestureDescription: The gesture to dispatch This value cannot be null.
callback AccessibilityService.GestureResultCallback?: The object to call back when the status of the gesture is known. If null, no status is reported.
handler Handler?: The handler on which to call back the callback object. If null, the object is called back on the service's main thread.
Return
Boolean true if the gesture is dispatched, false if not.

findFocus

Added in API level 21
open fun findFocus(focus: Int): AccessibilityNodeInfo!

Find the view that has the specified focus type. The search is performed across all windows.

Note: In order to access the windows your service has to declare the capability to retrieve window content by setting the android.R.styleable#AccessibilityService_canRetrieveWindowContent property in its meta-data. For details refer to SERVICE_META_DATA. Also the service has to opt-in to retrieve the interactive windows by setting the AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS flag. Otherwise, the search will be performed only in the active window.

Note: If the view with AccessibilityNodeInfo.FOCUS_INPUT is on an embedded view hierarchy which is embedded in a android.view.SurfaceView via android.view.SurfaceView#setChildSurfacePackage, there is a limitation that this API won't be able to find the node for the view. It's because views don't know about the embedded hierarchies. Instead, you could traverse all the nodes to find the focus.

Parameters
focus Int: The focus to find. One of AccessibilityNodeInfo.FOCUS_INPUT or AccessibilityNodeInfo.FOCUS_ACCESSIBILITY.
Return
AccessibilityNodeInfo! The node info of the focused view or null.

getAccessibilityButtonController

Added in API level 26
fun getAccessibilityButtonController(): AccessibilityButtonController

Returns the controller for the accessibility button within the system's navigation area. This instance may be used to query the accessibility button's state and register listeners for interactions with and state changes for the accessibility button when AccessibilityServiceInfo.FLAG_REQUEST_ACCESSIBILITY_BUTTON is set.

Note: Not all devices are capable of displaying the accessibility button within a navigation area, and as such, use of this class should be considered only as an optional feature or shortcut on supported device implementations.

Return
AccessibilityButtonController the accessibility button controller for this AccessibilityService This value cannot be null.

getAccessibilityButtonController

Added in API level 30
fun getAccessibilityButtonController(displayId: Int): AccessibilityButtonController

Returns the controller of specified logical display for the accessibility button within the system's navigation area. This instance may be used to query the accessibility button's state and register listeners for interactions with and state changes for the accessibility button when AccessibilityServiceInfo.FLAG_REQUEST_ACCESSIBILITY_BUTTON is set.

Note: Not all devices are capable of displaying the accessibility button within a navigation area, and as such, use of this class should be considered only as an optional feature or shortcut on supported device implementations.

Parameters
displayId Int: The logic display id, use Display.DEFAULT_DISPLAY for default display.
Return
AccessibilityButtonController the accessibility button controller for this AccessibilityService This value cannot be null.

getBrailleDisplayController

Added in API level 35
fun getBrailleDisplayController(): BrailleDisplayController

Returns the BrailleDisplayController which may be used to communicate with refreshable Braille displays that provide USB or Bluetooth Braille display HID support.

Return
BrailleDisplayController This value cannot be null.

getFingerprintGestureController

Added in API level 26
fun getFingerprintGestureController(): FingerprintGestureController

Get the controller for fingerprint gestures. This feature requires android.accessibilityservice.AccessibilityServiceInfo#CAPABILITY_CAN_REQUEST_FINGERPRINT_GESTURES. Note: The service must be connected before this method is called.
Requires android.Manifest.permission#USE_FINGERPRINT

Return
FingerprintGestureController The controller for fingerprint gestures, or null if gestures are unavailable.

getInputMethod

Added in API level 33
fun getInputMethod(): InputMethod?

Returns the InputMethod instance after the system calls onCreateInputMethod(), which may be used to input text or get editable text selection change notifications. It will return null if the accessibility service doesn't set the AccessibilityServiceInfo.FLAG_INPUT_METHOD_EDITOR flag or the system doesn't call onCreateInputMethod().

Return
InputMethod? the InputMethod instance

getMagnificationController

Added in API level 24
fun getMagnificationController(): AccessibilityService.MagnificationController

Returns the magnification controller, which may be used to query and modify the state of display magnification.

Note: In order to control magnification, your service must declare the capability by setting the android.R.styleable#AccessibilityService_canControlMagnification property in its meta-data. For more information, see SERVICE_META_DATA.

Return
AccessibilityService.MagnificationController the magnification controller This value cannot be null.

getRootInActiveWindow

Added in API level 16
open fun getRootInActiveWindow(): AccessibilityNodeInfo!

Gets the root node in the currently active window if this service can retrieve window content. The active window is the one that the user is currently touching or the window with input focus, if the user is not touching any window. It could be from any logical display.

Note: In order to access the root node your service has to declare the capability to retrieve window content by setting the android.R.styleable#AccessibilityService_canRetrieveWindowContent property in its meta-data. For details refer to SERVICE_META_DATA.

Return
AccessibilityNodeInfo! The root node if this service can retrieve window content.

getRootInActiveWindow

Added in API level 33
open fun getRootInActiveWindow(prefetchingStrategy: Int): AccessibilityNodeInfo?

Gets the root node in the currently active window if this service can retrieve window content. The active window is the one that the user is currently touching or the window with input focus, if the user is not touching any window. It could be from any logical display.

Return
AccessibilityNodeInfo? The root node if this service can retrieve window content. This value may be null.

getServiceInfo

Added in API level 16
fun getServiceInfo(): AccessibilityServiceInfo!

Gets the an AccessibilityServiceInfo describing this AccessibilityService. This method is useful if one wants to change some of the dynamically configurable properties at runtime.

Return
AccessibilityServiceInfo! The accessibility service info.

getSoftKeyboardController

Added in API level 24
fun getSoftKeyboardController(): AccessibilityService.SoftKeyboardController

Returns the soft keyboard controller, which may be used to query and modify the soft keyboard show mode.

Return
AccessibilityService.SoftKeyboardController the soft keyboard controller This value cannot be null.

getSystemActions

Added in API level 30
fun getSystemActions(): MutableList<AccessibilityNodeInfo.AccessibilityAction!>

Returns a list of system actions available in the system right now.

System actions that correspond to the global action constants will have matching action IDs. For example, an with id GLOBAL_ACTION_BACK will perform the back action.

These actions should be called by performGlobalAction.

Return
MutableList<AccessibilityNodeInfo.AccessibilityAction!> A list of available system actions. This value cannot be null.

getSystemService

Added in API level 4
open fun getSystemService(name: String): Any!

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.

Parameters
name String: Value is android.content.Context#POWER_SERVICE, android.content.Context#WINDOW_SERVICE, android.content.Context#LAYOUT_INFLATER_SERVICE, android.content.Context#ACCOUNT_SERVICE, android.content.Context#ACTIVITY_SERVICE, android.content.Context#ALARM_SERVICE, android.content.Context#NOTIFICATION_SERVICE, android.content.Context#ACCESSIBILITY_SERVICE, android.content.Context#CAPTIONING_SERVICE, android.content.Context#KEYGUARD_SERVICE, android.content.Context#LOCATION_SERVICE, android.content.Context#HEALTHCONNECT_SERVICE, android.content.Context#SEARCH_SERVICE, android.content.Context#SENSOR_SERVICE, android.content.Context.SENSOR_PRIVACY_SERVICE, android.content.Context#STORAGE_SERVICE, android.content.Context#STORAGE_STATS_SERVICE, android.content.Context#WALLPAPER_SERVICE, android.content.Context#VIBRATOR_MANAGER_SERVICE, android.content.Context#VIBRATOR_SERVICE, android.content.Context.THREAD_NETWORK_SERVICE, android.content.Context#CONNECTIVITY_SERVICE, android.content.Context.PAC_PROXY_SERVICE, android.content.Context.VCN_MANAGEMENT_SERVICE, android.content.Context#IPSEC_SERVICE, android.content.Context#VPN_MANAGEMENT_SERVICE, android.content.Context.TEST_NETWORK_SERVICE, android.content.Context#NETWORK_STATS_SERVICE, android.content.Context#WIFI_SERVICE, android.content.Context#WIFI_AWARE_SERVICE, android.content.Context#WIFI_P2P_SERVICE, android.content.Context.WIFI_SCANNING_SERVICE, android.content.Context#WIFI_RTT_RANGING_SERVICE, android.content.Context#NSD_SERVICE, android.content.Context#AUDIO_SERVICE, android.content.Context.AUDIO_DEVICE_VOLUME_SERVICE, android.content.Context.AUTH_SERVICE, android.content.Context#FINGERPRINT_SERVICE, android.content.Context#BIOMETRIC_SERVICE, android.content.Context.AUTHENTICATION_POLICY_SERVICE, android.content.Context#MEDIA_ROUTER_SERVICE, android.content.Context#TELEPHONY_SERVICE, android.content.Context#TELEPHONY_SUBSCRIPTION_SERVICE, android.content.Context#CARRIER_CONFIG_SERVICE, android.content.Context#EUICC_SERVICE, android.content.Context#TELECOM_SERVICE, android.content.Context#CLIPBOARD_SERVICE, android.content.Context#INPUT_METHOD_SERVICE, android.content.Context#TEXT_SERVICES_MANAGER_SERVICE, android.content.Context#TEXT_CLASSIFICATION_SERVICE, android.content.Context#APPWIDGET_SERVICE, android.content.Context.REBOOT_READINESS_SERVICE, android.content.Context.ROLLBACK_SERVICE, android.content.Context#DROPBOX_SERVICE, android.content.Context#DEVICE_POLICY_SERVICE, android.content.Context#UI_MODE_SERVICE, android.content.Context#DOWNLOAD_SERVICE, android.content.Context#NFC_SERVICE, android.content.Context#BLUETOOTH_SERVICE, android.content.Context#USB_SERVICE, android.content.Context#LAUNCHER_APPS_SERVICE, android.content.Context#INPUT_SERVICE, android.content.Context#DISPLAY_SERVICE, android.content.Context#USER_SERVICE, android.content.Context#RESTRICTIONS_SERVICE, android.content.Context#APP_OPS_SERVICE, android.content.Context#ROLE_SERVICE, android.content.Context#CAMERA_SERVICE, android.content.Context#PRINT_SERVICE, android.content.Context#CONSUMER_IR_SERVICE, android.content.Context#TV_INTERACTIVE_APP_SERVICE, android.content.Context#TV_INPUT_SERVICE, android.content.Context#USAGE_STATS_SERVICE, android.content.Context#MEDIA_SESSION_SERVICE, android.content.Context#MEDIA_COMMUNICATION_SERVICE, android.content.Context#BATTERY_SERVICE, android.content.Context#JOB_SCHEDULER_SERVICE, android.content.Context#PERSISTENT_DATA_BLOCK_SERVICE, android.content.Context#MEDIA_PROJECTION_SERVICE, android.content.Context#MIDI_SERVICE, android.content.Context.RADIO_SERVICE, android.content.Context#HARDWARE_PROPERTIES_SERVICE, android.content.Context#SHORTCUT_SERVICE, android.content.Context#SYSTEM_HEALTH_SERVICE, android.content.Context#COMPANION_DEVICE_SERVICE, android.content.Context#VIRTUAL_DEVICE_SERVICE, android.content.Context#CROSS_PROFILE_APPS_SERVICE, android.content.Context.PERMISSION_SERVICE, android.content.Context.LIGHTS_SERVICE, android.content.Context#LOCALE_SERVICE, android.content.Context.UWB_SERVICE, android.content.Context#MEDIA_METRICS_SERVICE, android.content.Context#DISPLAY_HASH_SERVICE, android.content.Context#CREDENTIAL_SERVICE, android.content.Context#DEVICE_LOCK_SERVICE, android.content.Context.VIRTUALIZATION_SERVICE, android.content.Context#GRAMMATICAL_INFLECTION_SERVICE, android.content.Context#SECURITY_STATE_SERVICE, android.content.Context#CONTACT_KEYS_SERVICE, android.content.Context.RANGING_SERVICE, android.content.Context.MEDIA_QUALITY_SERVICE, or android.content.Context.ADVANCED_PROTECTION_SERVICE This value cannot be null.
Return
Any! The service or null if the name does not exist.

getTouchInteractionController

Added in API level 33
fun getTouchInteractionController(displayId: Int): TouchInteractionController

Returns the touch interaction controller for the specified logical display, which may be used to detect gestures and otherwise control touch interactions. If AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE is disabled the controller's methods will have no effect.

Parameters
displayId Int: The logical display id, use Display.DEFAULT_DISPLAY for default display.
Return
TouchInteractionController the TouchExploration controller This value cannot be null.

getWindows

Added in API level 21
open fun getWindows(): MutableList<AccessibilityWindowInfo!>!

Gets the windows on the screen of the default display. This method returns only the windows that a sighted user can interact with, as opposed to all windows. For example, if there is a modal dialog shown and the user cannot touch anything behind it, then only the modal window will be reported (assuming it is the top one). For convenience the returned windows are ordered in a descending layer order, which is the windows that are on top are reported first. Since the user can always interact with the window that has input focus by typing, the focused window is always returned (even if covered by a modal window).

Note: In order to access the windows your service has to declare the capability to retrieve window content by setting the android.R.styleable#AccessibilityService_canRetrieveWindowContent property in its meta-data. For details refer to SERVICE_META_DATA. Also the service has to opt-in to retrieve the interactive windows by setting the AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS flag.

Return
MutableList<AccessibilityWindowInfo!>! The windows if there are windows and the service is can retrieve them, otherwise an empty list.

getWindowsOnAllDisplays

Added in API level 30
fun getWindowsOnAllDisplays(): SparseArray<MutableList<AccessibilityWindowInfo!>!>

Gets the windows on the screen of all displays. This method returns only the windows that a sighted user can interact with, as opposed to all windows. For example, if there is a modal dialog shown and the user cannot touch anything behind it, then only the modal window will be reported (assuming it is the top one). For convenience the returned windows are ordered in a descending layer order, which is the windows that are on top are reported first. Since the user can always interact with the window that has input focus by typing, the focused window is always returned (even if covered by a modal window).

Note: In order to access the windows your service has to declare the capability to retrieve window content by setting the android.R.styleable#AccessibilityService_canRetrieveWindowContent property in its meta-data. For details refer to SERVICE_META_DATA. Also the service has to opt-in to retrieve the interactive windows by setting the AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS flag.

Return
SparseArray<MutableList<AccessibilityWindowInfo!>!> The windows of all displays if there are windows and the service is can retrieve them, otherwise an empty list. The key of SparseArray is display ID. This value cannot be null.

isCacheEnabled

Added in API level 33
open fun isCacheEnabled(): Boolean

Returns true if the cache is enabled.

isNodeInCache

Added in API level 33
open fun isNodeInCache(node: AccessibilityNodeInfo): Boolean

Checks if node is in the cache.

Parameters
node AccessibilityNodeInfo: the node to check. This value cannot be null.
Return
Boolean true if node is in the cache.

onAccessibilityEvent

Added in API level 4
abstract fun onAccessibilityEvent(event: AccessibilityEvent!): Unit

Callback for android.view.accessibility.AccessibilityEvents.

Parameters
event AccessibilityEvent!: The new event. This event is owned by the caller and cannot be used after this method returns. Services wishing to use the event after this method returns should make a copy.

onBind

Added in API level 4
fun onBind(intent: Intent!): IBinder?

Implement to return the implementation of the internal accessibility service interface.

Parameters
intent Intent!: The Intent that was used to bind to this service, as given to android.content.Context#bindService. Note that any extras that were included with the Intent at that point will not be seen here.
Return
IBinder? Return an IBinder through which clients can call on to the service.

onCreateInputMethod

Added in API level 33
open fun onCreateInputMethod(): InputMethod

The default implementation returns our default InputMethod. Subclasses can override it to provide their own customized version. Accessibility services need to set the AccessibilityServiceInfo.FLAG_INPUT_METHOD_EDITOR flag to use input method APIs.

Return
InputMethod the InputMethod. This value cannot be null.

onGesture

Added in API level 30
open fun onGesture(gestureEvent: AccessibilityGestureEvent): Boolean

Called by the system when the user performs a specific gesture on the specific touch screen.

Note: To receive gestures an accessibility service must request that the device is in touch exploration mode by setting the AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE flag.

Note: The default implementation calls onGesture(int) when the touch screen is default display.

Parameters
gestureEvent AccessibilityGestureEvent: The information of gesture. This value cannot be null.
Return
Boolean Whether the gesture was handled.

onInterrupt

Added in API level 4
abstract fun onInterrupt(): Unit

Callback for interrupting the accessibility feedback.

onMotionEvent

Added in API level 34
open fun onMotionEvent(event: MotionEvent): Unit

Callback that allows an accessibility service to observe generic MotionEvents.

Prefer TouchInteractionController to observe and control touchscreen events, including touch gestures. If this or any enabled service is using AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE then onMotionEvent will not receive touchscreen events.

Note: The service must first request to listen to events using AccessibilityServiceInfo.setMotionEventSources. MotionEvents from sources in AccessibilityServiceInfo.getMotionEventSources() are not sent to the rest of the system. To stop listening to events from a given source, call AccessibilityServiceInfo.setMotionEventSources with that source removed.

Parameters
event MotionEvent: The event to be processed. This value cannot be null.

onSystemActionsChanged

Added in API level 30
open fun onSystemActionsChanged(): Unit

This is called when the system action list is changed.

performGlobalAction

Added in API level 16
fun performGlobalAction(action: Int): Boolean

Performs a global action. Such an action can be performed at any moment regardless of the current application or user location in that application. For example going back, going home, opening recents, etc.

Note: The global action ids themselves give no information about the current availability of their corresponding actions. To determine if a global action is available, use getSystemActions()

Parameters
action Int: The action to perform.
Return
Boolean Whether the action was successfully performed. Perform actions using ids like the id constants referenced below:

setAccessibilityFocusAppearance

Added in API level 31
open fun setAccessibilityFocusAppearance(
    strokeWidth: Int,
    color: Int
): Unit

Sets the strokeWidth and color of the accessibility focus rectangle.

Note: This setting persists until this or another active AccessibilityService changes it or the device reboots.

Parameters
strokeWidth Int: The stroke width of the rectangle in pixels. Setting this value to zero results in no focus rectangle being drawn.
color Int: The color of the rectangle.

setAnimationScale

Added in API level 33
open fun setAnimationScale(scale: Float): Unit

Sets the system settings values that control the scaling factor for animations. The scale controls the animation playback speed for animations that respect these settings. Animations that do not respect the settings values will not be affected by this function. A lower scale value results in a faster speed. A value of 0 disables animations entirely. When animations are disabled services receive window change events more quickly which can reduce the potential by confusion by reducing the time during which windows are in transition.

Parameters
scale Float: The scaling factor for all animations.

setCacheEnabled

Added in API level 33
open fun setCacheEnabled(enabled: Boolean): Boolean

Sets the cache status.

If enabled, enable the cache and prefetching. Otherwise, disable the cache and prefetching. Note: By default the cache is enabled.

Parameters
enabled Boolean: whether to enable or disable the cache.
Return
Boolean true if the cache and connection are not null, so the cache status is set.

setGestureDetectionPassthroughRegion

Added in API level 30
open fun setGestureDetectionPassthroughRegion(
    displayId: Int,
    region: Region
): Unit

When AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE is enabled, this function requests that touch interactions starting in the specified region of the screen bypass the gesture detector. There can only be one gesture detection passthrough region per display. Requesting a new gesture detection passthrough region clears the existing one. To disable this passthrough and return to the original behavior, pass in an empty region. When AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE is disabled this function has no effect.

Parameters
displayId Int: The display on which to set this region.
region Region: the region of the screen. This value cannot be null.

setServiceInfo

Added in API level 4
fun setServiceInfo(info: AccessibilityServiceInfo!): Unit

Sets the AccessibilityServiceInfo that describes this service.

Note: You can call this method any time but the info will be picked up after the system has bound to this service and when this method is called thereafter.

Parameters
info AccessibilityServiceInfo!: The info.

setTouchExplorationPassthroughRegion

Added in API level 30
open fun setTouchExplorationPassthroughRegion(
    displayId: Int,
    region: Region
): Unit

When AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE is enabled, this function requests that touch interactions starting in the specified region of the screen bypass the touch explorer and go straight to the view hierarchy. There can only be one touch exploration passthrough region per display. Requesting a new touch explorationpassthrough region clears the existing one. To disable this passthrough and return to the original behavior, pass in an empty region. When android.accessibilityservice.AccessibilityServiceInfo#FLAG_REQUEST_TOUCH_EXPLORATION_MODE is disabled this function has no effect.

Parameters
displayId Int: The display on which to set this region.
region Region: the region of the screen . This value cannot be null.

takeScreenshot

Added in API level 30
open fun takeScreenshot(
    displayId: Int,
    executor: Executor,
    callback: AccessibilityService.TakeScreenshotCallback
): Unit

Takes a screenshot of the specified display and returns it via an AccessibilityService.ScreenshotResult. You can use Bitmap.wrapHardwareBuffer to construct the bitmap from the ScreenshotResult's payload.

Note: In order to take screenshot your service has to declare the capability to take screenshot by setting the android.R.styleable#AccessibilityService_canTakeScreenshot property in its meta-data. For details refer to SERVICE_META_DATA.

Parameters
displayId Int: The logic display id, must be Display.DEFAULT_DISPLAY for default display.
executor Executor: Executor on which to run the callback. This value cannot be null. Callback and listener events are dispatched through this Executor, providing an easy way to control which thread is used. To dispatch events through the main thread of your application, you can use Context.getMainExecutor(). Otherwise, provide an Executor that dispatches to an appropriate thread.
callback AccessibilityService.TakeScreenshotCallback: The callback invoked when taking screenshot has succeeded or failed. See TakeScreenshotCallback for details. This value cannot be null.

takeScreenshotOfWindow

Added in API level 34
open fun takeScreenshotOfWindow(
    accessibilityWindowId: Int,
    executor: Executor,
    callback: AccessibilityService.TakeScreenshotCallback
): Unit

Takes a screenshot of the specified window and returns it via an AccessibilityService.ScreenshotResult. You can use Bitmap.wrapHardwareBuffer to construct the bitmap from the ScreenshotResult's payload.

Note: In order to take screenshots your service has to declare the capability to take screenshot by setting the android.R.styleable#AccessibilityService_canTakeScreenshot property in its meta-data. For details refer to SERVICE_META_DATA.

Both this method and takeScreenshot can be used for machine learning-based visual screen understanding. Use takeScreenshotOfWindow if your target window might be visually underneath an accessibility overlay (from your or another accessibility service) in order to capture the window contents without the screenshot being covered by the overlay contents drawn on the screen.

Parameters
accessibilityWindowId Int: The window id, from AccessibilityWindowInfo.getId().
executor Executor: Executor on which to run the callback. This value cannot be null. Callback and listener events are dispatched through this Executor, providing an easy way to control which thread is used. To dispatch events through the main thread of your application, you can use Context.getMainExecutor(). Otherwise, provide an Executor that dispatches to an appropriate thread.
callback AccessibilityService.TakeScreenshotCallback: The callback invoked when taking screenshot has succeeded or failed. See TakeScreenshotCallback for details. This value cannot be null.

See Also

Protected methods

onGesture

Added in API level 16
Deprecated in API level 30
protected open fun onGesture(gestureId: Int): Boolean

Deprecated: Override onGesture(android.accessibilityservice.AccessibilityGestureEvent) instead.

Called by onGesture(android.accessibilityservice.AccessibilityGestureEvent) when the user performs a specific gesture on the default display. Note: To receive gestures an accessibility service must request that the device is in touch exploration mode by setting the AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE flag.

Parameters
gestureId Int: The unique id of the performed gesture.
Return
Boolean Whether the gesture was handled.

onKeyEvent

Added in API level 18
protected open fun onKeyEvent(event: KeyEvent!): Boolean

Callback that allows an accessibility service to observe the key events before they are passed to the rest of the system. This means that the events are first delivered here before they are passed to the device policy, the input method, or applications.

Note: It is important that key events are handled in such a way that the event stream that would be passed to the rest of the system is well-formed. For example, handling the down event but not the up event and vice versa would generate an inconsistent event stream.

Note: The key events delivered in this method are copies and modifying them will have no effect on the events that will be passed to the system. This method is intended to perform purely filtering functionality.

Parameters
event KeyEvent!: The event to be processed. This event is owned by the caller and cannot be used after this method returns. Services wishing to use the event after this method returns should make a copy.
Return
Boolean If true then the event will be consumed and not delivered to applications, otherwise it will be delivered as usual.

onServiceConnected

Added in API level 4
protected open fun onServiceConnected(): Unit

This method is a part of the AccessibilityService lifecycle and is called after the system has successfully bound to the service. If is convenient to use this method for setting the AccessibilityServiceInfo.