InputMethodService


public class InputMethodService
extends AbstractInputMethodService

java.lang.Object
   ↳ android.content.Context
     ↳ android.content.ContextWrapper
       ↳ android.app.Service
         ↳ android.inputmethodservice.AbstractInputMethodService
           ↳ android.inputmethodservice.InputMethodService


InputMethodService provides a standard implementation of an InputMethod, which final implementations can derive from and customize. See the base class AbstractInputMethodService and the InputMethod interface for more information on the basics of writing input methods.

In addition to the normal Service lifecycle methods, this class introduces some new specific callbacks that most subclasses will want to make use of:

An input method has significant discretion in how it goes about its work: the InputMethodService provides a basic framework for standard UI elements (input view, candidates view, and running in fullscreen mode), but it is up to a particular implementor to decide how to use them. For example, one input method could implement an input area with a keyboard, another could allow the user to draw text, while a third could have no input area (and thus not be visible to the user) but instead listen to audio and perform text to speech conversion.

In the implementation provided here, all of these elements are placed together in a single window managed by the InputMethodService. It will execute callbacks as it needs information about them, and provides APIs for programmatic control over them. They layout of these elements is explicitly defined:

  • The soft input view, if available, is placed at the bottom of the screen.
  • The candidates view, if currently shown, is placed above the soft input view.
  • If not running fullscreen, the application is moved or resized to be above these views; if running fullscreen, the window will completely cover the application and its top part will contain the extract text of what is currently being edited by the application.

Soft Input View

Central to most input methods is the soft input view. This is where most user interaction occurs: pressing on soft keys, drawing characters, or however else your input method wants to generate text. Most implementations will simply have their own view doing all of this work, and return a new instance of it when onCreateInputView() is called. At that point, as long as the input view is visible, you will see user interaction in that view and can call back on the InputMethodService to interact with the application as appropriate.

There are some situations where you want to decide whether or not your soft input view should be shown to the user. This is done by implementing the onEvaluateInputViewShown() to return true or false based on whether it should be shown in the current environment. If any of your state has changed that may impact this, call updateInputViewShown() to have it re-evaluated. The default implementation always shows the input view unless there is a hard keyboard available, which is the appropriate behavior for most input methods.

Candidates View

Often while the user is generating raw text, an input method wants to provide them with a list of possible interpretations of that text that can be selected for use. This is accomplished with the candidates view, and like the soft input view you implement onCreateCandidatesView() to instantiate your own view implementing your candidates UI.

Management of the candidates view is a little different than the input view, because the candidates view tends to be more transient, being shown only when there are possible candidates for the current text being entered by the user. To control whether the candidates view is shown, you use setCandidatesViewShown(boolean). Note that because the candidate view tends to be shown and hidden a lot, it does not impact the application UI in the same way as the soft input view: it will never cause application windows to resize, only cause them to be panned if needed for the user to see the current focus.

Fullscreen Mode

Sometimes your input method UI is too large to integrate with the application UI, so you just want to take over the screen. This is accomplished by switching to full-screen mode, causing the input method window to fill the entire screen and add its own "extracted text" editor showing the user the text that is being typed. Unlike the other UI elements, there is a standard implementation for the extract editor that you should not need to change. The editor is placed at the top of the IME, above the input and candidates views.

Similar to the input view, you control whether the IME is running in fullscreen mode by implementing onEvaluateFullscreenMode() to return true or false based on whether it should be fullscreen in the current environment. If any of your state has changed that may impact this, call updateFullscreenMode() to have it re-evaluated. The default implementation selects fullscreen mode when the screen is in a landscape orientation, which is appropriate behavior for most input methods that have a significant input area.

When in fullscreen mode, you have some special requirements because the user can not see the application UI. In particular, you should implement onDisplayCompletions(android.view.inputmethod.CompletionInfo[]) to show completions generated by your application, typically in your candidates view like you would normally show candidates.

Generating Text

The key part of an IME is of course generating text for the application. This is done through calls to the InputConnection interface to the application, which can be retrieved from getCurrentInputConnection(). This interface allows you to generate raw key events or, if the target supports it, directly edit in strings of candidates and committed text.

Information about what the target is expected and supports can be found through the EditorInfo class, which is retrieved with getCurrentInputEditorInfo() method. The most important part of this is EditorInfo.inputType; in particular, if this is EditorInfo.TYPE_NULL, then the target does not support complex edits and you need to only deliver raw key events to it. An input method will also want to look at other values here, to for example detect password mode, auto complete text views, phone number entry, etc.

When the user switches between input targets, you will receive calls to onFinishInput() and onStartInput(android.view.inputmethod.EditorInfo, boolean). You can use these to reset and initialize your input state for the current target. For example, you will often want to clear any input state, and update a soft keyboard to be appropriate for the new inputType.

Summary

Nested classes

class InputMethodService.InputMethodImpl

Concrete implementation of AbstractInputMethodService.AbstractInputMethodImpl that provides all of the standard behavior for an input method. 

class InputMethodService.InputMethodSessionImpl

Concrete implementation of AbstractInputMethodService.AbstractInputMethodSessionImpl that provides all of the standard behavior for an input method session. 

class InputMethodService.Insets

Information about where interesting parts of the input method UI appear. 

XML attributes

android:imeExtractEnterAnimation Animation to use when showing the fullscreen extract UI after it had previously been hidden. 
android:imeExtractExitAnimation Animation to use when hiding the fullscreen extract UI after it had previously been shown. 
android:imeFullscreenBackground Background to use for entire input method when it is being shown in fullscreen mode with the extract view, to ensure that it completely covers the application. 

Constants

int BACK_DISPOSITION_ADJUST_NOTHING

Asks the system to not adjust the back button affordance even when the software keyboard is shown.

int BACK_DISPOSITION_DEFAULT

Allows the system to optimize the back button affordance based on the presence of software keyboard.

int BACK_DISPOSITION_WILL_DISMISS

This constant was deprecated in API level 28. on Build.VERSION_CODES.P and later devices, this flag is handled as a synonym of BACK_DISPOSITION_DEFAULT. On Build.VERSION_CODES.O_MR1 and prior devices, expected behavior of this mode had not been well defined. In AOSP implementation running on devices that have navigation bar, specifying this flag could change the software back button to "Dismiss" icon no matter whether the software keyboard is shown or not, but there would be no easy way to restore the icon state even after IME lost the connection to the application. To avoid user confusions, do not specify this mode anyway

int BACK_DISPOSITION_WILL_NOT_DISMISS

This constant was deprecated in API level 28. on Build.VERSION_CODES.P and later devices, this flag is handled as a synonym of BACK_DISPOSITION_DEFAULT. On Build.VERSION_CODES.O_MR1 and prior devices, expected behavior of this mode had not been well defined. Most likely the end result would be the same as BACK_DISPOSITION_DEFAULT. Either way it is not recommended to use this mode

Inherited constants

int START_CONTINUATION_MASK

Bits returned by onStartCommand(Intent, int, int) describing how to continue the service if it is killed.

int START_FLAG_REDELIVERY

This flag is set in onStartCommand(Intent, int, int) 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(Intent, int, int) 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(Intent, int, int): if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), 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).

int START_REDELIVER_INTENT

Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then it will be scheduled for a restart and the last delivered Intent re-delivered to it again via onStartCommand(Intent, int, int).

int START_STICKY

Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent.

int START_STICKY_COMPATIBILITY

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

int STOP_FOREGROUND_DETACH

Selector for stopForeground(int): if set, the notification previously supplied to startForeground(int, Notification) will be detached from the service's lifecycle.

int STOP_FOREGROUND_LEGACY

This constant was deprecated in API level 33. Use STOP_FOREGROUND_DETACH instead. The legacy behavior was inconsistent, leading to bugs around unpredictable results.

int STOP_FOREGROUND_REMOVE

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

String ACCESSIBILITY_SERVICE

Use with getSystemService(java.lang.String) to retrieve a 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 AccountManager for receiving intents at a time of your choosing.

String ACTIVITY_SERVICE

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

String ADVANCED_PROTECTION_SERVICE

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

String ALARM_SERVICE

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

String APPWIDGET_SERVICE

Use with getSystemService(java.lang.String) to retrieve a 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 AppOpsManager for tracking application operations on the device.

String APP_SEARCH_SERVICE

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

String AUDIO_SERVICE

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

String BATTERY_SERVICE

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

int BIND_ABOVE_CLIENT

Flag for bindService(Intent, BindServiceFlags, Executor, ServiceConnection): indicates that the client application binding to this service considers the service to be more important than the app itself.

int BIND_ADJUST_WITH_ACTIVITY

Flag for bindService(Intent, BindServiceFlags, Executor, ServiceConnection): 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(Intent, BindServiceFlags, Executor, ServiceConnection): If binding from an app that is visible, the bound service is allowed to start an activity from background.

int BIND_ALLOW_OOM_MANAGEMENT

Flag for bindService(Intent, BindServiceFlags, Executor, ServiceConnection): allow the process hosting the bound service to go through its normal memory management.

int BIND_AUTO_CREATE

Flag for bindService(Intent, BindServiceFlags, Executor, ServiceConnection): automatically create the service as long as the binding exists.

int BIND_DEBUG_UNBIND

Flag for bindService(Intent, BindServiceFlags, Executor, ServiceConnection): include debugging help for mismatched calls to unbind.

int BIND_EXTERNAL_SERVICE

Flag for bindService(Intent, BindServiceFlags, Executor, ServiceConnection): The service being bound is an isolated, external service.

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(Intent, BindServiceFlags, Executor, ServiceConnection): this service is very important to the client, so should be brought to the foreground process level when the client is.

int BIND_INCLUDE_CAPABILITIES

Flag for bindService(Intent, BindServiceFlags, Executor, ServiceConnection): 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.

int BIND_NOT_FOREGROUND

Flag for bindService(Intent, BindServiceFlags, Executor, ServiceConnection): don't allow this binding to raise the target service's process to the foreground scheduling priority.

int BIND_NOT_PERCEPTIBLE

Flag for bindService(Intent, BindServiceFlags, Executor, ServiceConnection): If binding from an app that is visible or user-perceptible, lower the target service's importance to below the perceptible level.

int BIND_PACKAGE_ISOLATED_PROCESS

Flag for bindIsolatedService(Intent, BindServiceFlags, String, Executor, ServiceConnection): Bind the service into a shared isolated process, but only with other isolated services from the same package that declare the same process name.

int BIND_SHARED_ISOLATED_PROCESS

Flag for bindIsolatedService(Intent, BindServiceFlags, String, Executor, ServiceConnection): Bind the service into a shared isolated process.

int BIND_WAIVE_PRIORITY

Flag for bindService(Intent, BindServiceFlags, Executor, ServiceConnection): don't impact the scheduling or memory management priority of the target service's hosting process.

String BIOMETRIC_SERVICE

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

String BLOB_STORE_SERVICE

Use with getSystemService(java.lang.String) to retrieve a BlobStoreManager 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 BluetoothManager for using Bluetooth.

String BUGREPORT_SERVICE

Service to capture a bugreport.

String CAMERA_SERVICE

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

String CAPTIONING_SERVICE

Use with getSystemService(java.lang.String) to retrieve a 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 CarrierConfigManager for reading carrier configuration values.

String CLIPBOARD_SERVICE

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

String COMPANION_DEVICE_SERVICE

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

String CONNECTIVITY_DIAGNOSTICS_SERVICE

Use with getSystemService(java.lang.String) to retrieve a ConnectivityDiagnosticsManager 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 ConnectivityManager for handling management of network connections.

String CONSUMER_IR_SERVICE

Use with getSystemService(java.lang.String) to retrieve a 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(String, int): ignore any security restrictions on the Context being requested, allowing it to always be loaded.

int CONTEXT_INCLUDE_CODE

Flag for use with createPackageContext(String, int): include the application code with the context.

int CONTEXT_RESTRICTED

Flag for use with createPackageContext(String, int): a restricted context may disable specific features.

String CREDENTIAL_SERVICE

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

String CROSS_PROFILE_APPS_SERVICE

Use with getSystemService(java.lang.String) to retrieve a 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 DeviceLockManager.

String DEVICE_POLICY_SERVICE

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

String DISPLAY_HASH_SERVICE

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

String DISPLAY_SERVICE

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

String DOMAIN_VERIFICATION_SERVICE

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

String DOWNLOAD_SERVICE

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

String DROPBOX_SERVICE

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

String EUICC_SERVICE

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

String FILE_INTEGRITY_SERVICE

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

String FINGERPRINT_SERVICE

Use with getSystemService(java.lang.String) to retrieve a 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 HardwarePropertiesManager for accessing the hardware properties service.

String HEALTHCONNECT_SERVICE

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

String INPUT_METHOD_SERVICE

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

String INPUT_SERVICE

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

String IPSEC_SERVICE

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

String JOB_SCHEDULER_SERVICE

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

String KEYGUARD_SERVICE

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

String KEYSTORE_SERVICE

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

String LAUNCHER_APPS_SERVICE

Use with getSystemService(java.lang.String) to retrieve a 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 LayoutInflater for inflating layout resources in this context.

String LOCALE_SERVICE

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

String LOCATION_SERVICE

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

String MEDIA_COMMUNICATION_SERVICE

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

String MEDIA_METRICS_SERVICE

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

String MEDIA_PROJECTION_SERVICE

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

String MEDIA_QUALITY_SERVICE

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

String MEDIA_ROUTER_SERVICE

Use with getSystemService(Class) to retrieve a MediaRouter for controlling and managing routing of media.

String MEDIA_SESSION_SERVICE

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

String MIDI_SERVICE

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

int MODE_APPEND

File creation mode: for use with openFileOutput(String, int), 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

This constant was deprecated in API level 23. MODE_MULTI_PROCESS does not work reliably in some versions of Android, and furthermore does not provide any mechanism for reconciling concurrent modifications across processes. Applications should not attempt to use it. Instead, they should use an explicit cross-process data management approach such as ContentProvider.

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

This constant was deprecated in API level 17. Creating world-readable files is very dangerous, and likely to cause security holes in applications. It is strongly discouraged; instead, applications should use more formal mechanism for interactions such as ContentProvider, BroadcastReceiver, and Service. There are no guarantees that this access mode will remain on a file, such as when it goes through a backup and restore.

int MODE_WORLD_WRITEABLE

This constant was deprecated in API level 17. Creating world-writable files is very dangerous, and likely to cause security holes in applications. It is strongly discouraged; instead, applications should use more formal mechanism for interactions such as ContentProvider, BroadcastReceiver, and Service. There are no guarantees that this access mode will remain on a file, such as when it goes through a backup and restore.

String NETWORK_STATS_SERVICE

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

String NFC_SERVICE

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

String NOTIFICATION_SERVICE

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

String NSD_SERVICE

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

String OVERLAY_SERVICE

Use with getSystemService(java.lang.String) to retrieve a OverlayManager 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 PerformanceHintManager for accessing the performance hinting service.

String PERSISTENT_DATA_BLOCK_SERVICE

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

String POWER_SERVICE

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

String PRINT_SERVICE

PrintManager for printing and managing printers and print tasks.

String PROFILING_SERVICE

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

int RECEIVER_EXPORTED

Flag for registerReceiver(BroadcastReceiver, IntentFilter): The receiver can receive broadcasts from other Apps.

int RECEIVER_NOT_EXPORTED

Flag for registerReceiver(BroadcastReceiver, IntentFilter): The receiver cannot receive broadcasts from other Apps.

int RECEIVER_VISIBLE_TO_INSTANT_APPS

Flag for registerReceiver(BroadcastReceiver, IntentFilter): The receiver can receive broadcasts from Instant Apps.

String RESTRICTIONS_SERVICE

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

String ROLE_SERVICE

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

String SATELLITE_SERVICE

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

String SEARCH_SERVICE

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

String SECURITY_STATE_SERVICE

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

String SENSOR_SERVICE

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

String SHORTCUT_SERVICE

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

String STATUS_BAR_SERVICE

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

String STORAGE_SERVICE

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

String STORAGE_STATS_SERVICE

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

String SYSTEM_HEALTH_SERVICE

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

String TELECOM_SERVICE

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

String TELEPHONY_IMS_SERVICE

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

String TELEPHONY_SERVICE

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

String TELEPHONY_SUBSCRIPTION_SERVICE

Use with getSystemService(java.lang.String) to retrieve a 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 TextServicesManager for accessing text services.

String TV_AD_SERVICE

Use with getSystemService(java.lang.String) to retrieve a 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 TvInputManager for interacting with TV inputs on the device.

String TV_INTERACTIVE_APP_SERVICE

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

String UI_MODE_SERVICE

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

String USAGE_STATS_SERVICE

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

String USB_SERVICE

Use with getSystemService(java.lang.String) to retrieve a UsbManager 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 UserManager for managing users on devices that support multiple users.

String VIBRATOR_MANAGER_SERVICE

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

String VIBRATOR_SERVICE

This constant was deprecated in API level 31. Use VibratorManager to retrieve the default system vibrator.

String VIRTUAL_DEVICE_SERVICE

Use with getSystemService(java.lang.String) to retrieve a VirtualDeviceManager for managing virtual devices.

String VPN_MANAGEMENT_SERVICE

Use with getSystemService(java.lang.String) to retrieve a 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 WifiAwareManager for handling management of Wi-Fi Aware.

String WIFI_P2P_SERVICE

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

String WIFI_RTT_RANGING_SERVICE

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

String WIFI_SERVICE

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

String WINDOW_SERVICE

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

int TRIM_MEMORY_BACKGROUND

Level for onTrimMemory(int): the process has gone on to the LRU list.

int TRIM_MEMORY_COMPLETE

This constant was deprecated in API level 35. Apps are not notified of this level since API level 34

int TRIM_MEMORY_MODERATE

This constant was deprecated in API level 35. Apps are not notified of this level since API level 34

int TRIM_MEMORY_RUNNING_CRITICAL

This constant was deprecated in API level 35. Apps are not notified of this level since API level 34

int TRIM_MEMORY_RUNNING_LOW

This constant was deprecated in API level 35. Apps are not notified of this level since API level 34

int TRIM_MEMORY_RUNNING_MODERATE

This constant was deprecated in API level 35. Apps are not notified of this level since API level 34

int TRIM_MEMORY_UI_HIDDEN

Level for onTrimMemory(int): the process had been showing a user interface, and is no longer doing so.

Public constructors

InputMethodService()

Public methods

boolean enableHardwareAcceleration()

This method was deprecated in API level 21. Starting in API 21, hardware acceleration is always enabled on capable devices

final void finishConnectionlessStylusHandwriting(CharSequence text)

Finishes the current connectionless stylus handwriting session and delivers the result.

final void finishStylusHandwriting()

Finish the current stylus handwriting session.

int getBackDisposition()

Retrieves the current disposition mode that indicates the expected back button affordance.

int getCandidatesHiddenVisibility()

Returns the visibility mode (either View.INVISIBLE or View.GONE) of the candidates view when it is not shown.

InputBinding getCurrentInputBinding()

Return the currently active InputBinding for the input method, or null if there is none.

InputConnection getCurrentInputConnection()

Retrieve the currently active InputConnection that is bound to the input method, or null if there is none.

EditorInfo getCurrentInputEditorInfo()
boolean getCurrentInputStarted()
int getInputMethodWindowRecommendedHeight()

This method was deprecated in API level 29. the actual behavior of this method has never been well defined. You cannot use this method in a reliable and predictable way

LayoutInflater getLayoutInflater()
int getMaxWidth()

Return the maximum width, in pixels, available the input method.

static final Duration getStylusHandwritingIdleTimeoutMax()

Returns the maximum stylus handwriting session idle-timeout for use with setStylusHandwritingSessionTimeout(java.time.Duration).

final Duration getStylusHandwritingSessionTimeout()

Returns the duration after which an ongoing stylus handwriting session that hasn't received new MotionEvents will time out and finishStylusHandwriting() will be called.

final Window getStylusHandwritingWindow()

Returns the stylus handwriting inking window.

Object getSystemService(String name)

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

CharSequence getTextForImeAction(int imeOptions)

Return text that can be used as a button label for the given EditorInfo.imeOptions.

Dialog getWindow()
void hideStatusIcon()
void hideWindow()
boolean isExtractViewShown()

Return whether the fullscreen extract view is shown.

boolean isFullscreenMode()

Return whether the input method is currently running in fullscreen mode.

boolean isInputViewShown()

Return whether the soft input view is currently shown to the user.

boolean isShowInputRequested()

Returns true if we have been asked to show our input view.

void onAppPrivateCommand(String action, Bundle data)

Not implemented in this class.

void onBindInput()

Called when a new client has bound to the input method.

void onComputeInsets(InputMethodService.Insets outInsets)

Compute the interesting insets into your UI.

void onConfigurationChanged(Configuration newConfig)

Take care of handling configuration changes.

void onConfigureWindow(Window win, boolean isFullscreen, boolean isCandidatesOnly)

Update the given window's parameters for the given mode.

void onCreate()

Called by the system when the service is first created.

View onCreateCandidatesView()

Create and return the view hierarchy used to show candidates.

View onCreateExtractTextView()

Called by the framework to create the layout for showing extracted text.

InlineSuggestionsRequest onCreateInlineSuggestionsRequest(Bundle uiExtras)

Called when Autofill is requesting an InlineSuggestionsRequest from the IME.

AbstractInputMethodService.AbstractInputMethodImpl onCreateInputMethodInterface()

This method is deprecated. Overriding or calling this method is strongly discouraged. A future version of Android will remove the ability to use this method. Use the callbacks on InputMethodService as InputMethodService.onBindInput(), InputMethodService.onUnbindInput(), InputMethodService.onWindowShown(), InputMethodService.onWindowHidden(), etc.

AbstractInputMethodService.AbstractInputMethodSessionImpl onCreateInputMethodSessionInterface()

This method is deprecated. Overriding or calling this method is strongly discouraged. Most methods in InputMethodSessionImpl have corresponding callbacks. Use InputMethodService.onFinishInput(), InputMethodService.onDisplayCompletions(CompletionInfo[]), InputMethodService.onUpdateExtractedText(int, ExtractedText), InputMethodService.onUpdateSelection(int, int, int, int, int, int) instead.

View onCreateInputView()

Create and return the view hierarchy used for the input area (such as a soft keyboard).

void onCustomImeSwitcherButtonRequestedVisible(boolean visible)

Called when the requested visibility of a custom IME Switcher button changes.

void onDestroy()

Called by the system to notify a Service that it is no longer used and is being removed. If you override this method you must call through to the superclass implementation.

void onDisplayCompletions(CompletionInfo[] completions)

Called when the application has reported auto-completion candidates that it would like to have the input method displayed.

boolean onEvaluateFullscreenMode()

Override this to control when the input method should run in fullscreen mode.

boolean onEvaluateInputViewShown()

Override this to control when the soft input area should be shown to the user.

boolean onExtractTextContextMenuItem(int id)

This is called when the user has selected a context menu item from the extracted text view, when running in fullscreen mode.

void onExtractedCursorMovement(int dx, int dy)

This is called when the user has performed a cursor movement in the extracted text view, when it is running in fullscreen mode.

void onExtractedSelectionChanged(int start, int end)

This is called when the user has moved the cursor in the extracted text view, when running in fullsreen mode.

void onExtractedTextClicked()

This is called when the user has clicked on the extracted text view, when running in fullscreen mode.

void onExtractingInputChanged(EditorInfo ei)

This is called when, while currently displayed in extract mode, the current input target changes.

void onFinishCandidatesView(boolean finishingInput)

Called when the candidates view is being hidden from the user.

void onFinishInput()

Called to inform the input method that text input has finished in the last editor.

void onFinishInputView(boolean finishingInput)

Called when the input view is being hidden from the user.

void onFinishStylusHandwriting()

Called when the current stylus handwriting session was finished (either by the system or via finishStylusHandwriting().

boolean onGenericMotionEvent(MotionEvent event)

Override this to intercept generic motion events before they are processed by the application.

void onInitializeInterface()

This is a hook that subclasses can use to perform initialization of their interface.

boolean onInlineSuggestionsResponse(InlineSuggestionsResponse response)

Called when Autofill responds back with InlineSuggestionsResponse containing inline suggestions.

boolean onKeyDown(int keyCode, KeyEvent event)

Called back when a KeyEvent is forwarded from the target application.

boolean onKeyLongPress(int keyCode, KeyEvent event)

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

boolean onKeyMultiple(int keyCode, int count, KeyEvent event)

Override this to intercept special key multiple events before they are processed by the application.

boolean onKeyUp(int keyCode, KeyEvent event)

Override this to intercept key up events before they are processed by the application.

void onPrepareStylusHandwriting()

Called to prepare stylus handwriting.

boolean onShouldVerifyKeyEvent(KeyEvent keyEvent)

Received by the IME before dispatch to onKeyDown(int, android.view.KeyEvent) to let the system know if the KeyEvent needs to be verified that it originated from the system.

boolean onShowInputRequested(int flags, boolean configChange)

The system has decided that it may be time to show your input method.

void onStartCandidatesView(EditorInfo editorInfo, boolean restarting)

Called when only the candidates view has been shown for showing processing as the user enters text through a hard keyboard.

boolean onStartConnectionlessStylusHandwriting(int inputType, CursorAnchorInfo cursorAnchorInfo)

Called when an app requests to start a connectionless stylus handwriting session using one of InputMethodManager.startConnectionlessStylusHandwriting(View, CursorAnchorInfo, Executor, ConnectionlessHandwritingCallback), InputMethodManager.startConnectionlessStylusHandwritingForDelegation(android.view.View, android.view.inputmethod.CursorAnchorInfo, java.util.concurrent.Executor, android.view.inputmethod.ConnectionlessHandwritingCallback), or InputMethodManager.startConnectionlessStylusHandwritingForDelegation(android.view.View, android.view.inputmethod.CursorAnchorInfo, java.lang.String, java.util.concurrent.Executor, android.view.inputmethod.ConnectionlessHandwritingCallback).

void onStartInput(EditorInfo attribute, boolean restarting)

Called to inform the input method that text input has started in an editor.

void onStartInputView(EditorInfo editorInfo, boolean restarting)

Called when the input view is being shown and input has started on a new editor.

boolean onStartStylusHandwriting()

Called when an app requests stylus handwriting InputMethodManager.startStylusHandwriting(View).

void onStylusHandwritingMotionEvent(MotionEvent motionEvent)

Called after onStartStylusHandwriting() returns true for every Stylus MotionEvent.

boolean onTrackballEvent(MotionEvent event)

Override this to intercept trackball motion events before they are processed by the application.

void onUnbindInput()

Called when the previous bound client is no longer associated with the input method.

void onUpdateCursor(Rect newCursor)

This method was deprecated in API level 21. Use onUpdateCursorAnchorInfo(android.view.inputmethod.CursorAnchorInfo) instead.

void onUpdateCursorAnchorInfo(CursorAnchorInfo cursorAnchorInfo)

Called when the application has reported a new location of its text insertion point and characters in the composition string.

void onUpdateEditorToolType(int toolType)

Called when the user tapped or clicked an editor.

void onUpdateExtractedText(int token, ExtractedText text)

Called when the application has reported new extracted text to be shown due to changes in its current text state.

void onUpdateExtractingViews(EditorInfo ei)

Called when the fullscreen-mode extracting editor info has changed, to update the state of its UI such as the action buttons shown.

void onUpdateExtractingVisibility(EditorInfo ei)

Called when the fullscreen-mode extracting editor info has changed, to determine whether the extracting (extract text and candidates) portion of the UI should be shown.

void onUpdateSelection(int oldSelStart, int oldSelEnd, int newSelStart, int newSelEnd, int candidatesStart, int candidatesEnd)

Called when the application has reported a new selection region of the text.

void onViewClicked(boolean focusChanged)

This method was deprecated in API level 29. The method may not be called for composite View that works as a giant "Canvas", which can host its own UI hierarchy and sub focus state. WebView is a good example. Application / IME developers should not rely on this method. If your goal is just being notified when an on-going input is interrupted, simply monitor onFinishInput(). If your goal is to know what MotionEvent.getToolType(int) clicked on editor, use onUpdateEditorToolType(int) instead.

void onWindowHidden()

Called when the input method window has been hidden from the user, after previously being visible.

void onWindowShown()

Called immediately before the input method window is shown to the user.

void requestHideSelf(int flags)

Close this input method's soft input area, removing it from the display.

final void requestShowSelf(int flags)

Show the input method's soft input area, so the user sees the input method window and can interact with it.

boolean sendDefaultEditorAction(boolean fromEnterKey)

Ask the input target to execute its default action via InputConnection.performEditorAction().

void sendDownUpKeyEvents(int keyEventCode)

Send the given key event code (as defined by KeyEvent) to the current input connection is a key down + key up event pair.

void sendKeyChar(char charCode)

Send the given UTF-16 character to the current input connection.

void setBackDisposition(int disposition)

Sets the disposition mode that indicates the expected affordance for the back button.

void setCandidatesView(View view)

Replaces the current candidates view with a new one.

void setCandidatesViewShown(boolean shown)

Controls the visibility of the candidates display area.

void setExtractView(View view)
void setExtractViewShown(boolean shown)

Controls the visibility of the extracted text area.

void setInputView(View view)

Replaces the current input view with a new one.

final void setStylusHandwritingRegion(Region handwritingRegion)

Sets a new stylus handwriting region as user continues to write on an editor on screen.

final void setStylusHandwritingSessionTimeout(Duration duration)

Sets the duration after which an ongoing stylus handwriting session that hasn't received new MotionEvents will time out and finishStylusHandwriting() will be called.

void setTheme(int theme)

You can call this to customize the theme used by your IME's window.

final boolean shouldOfferSwitchingToNextInputMethod()

Returns true if the current IME needs to offer the users ways to switch to a next input method (e.g. a globe key.).

void showStatusIcon(int iconResId)
void showWindow(boolean showInput)
void switchInputMethod(String id)

Force switch to a new input method, as identified by id.

final void switchInputMethod(String id, InputMethodSubtype subtype)

Force switch to a new input method, as identified by id.

final boolean switchToNextInputMethod(boolean onlyCurrentIme)

Force switch to the next input method and subtype.

final boolean switchToPreviousInputMethod()

Force switch to the last used input method and subtype.

void updateFullscreenMode()

Re-evaluate whether the input method should be running in fullscreen mode, and update its UI if this has changed since the last time it was evaluated.

void updateInputViewShown()

Re-evaluate whether the soft input area should currently be shown, and update its UI if this has changed since the last time it was evaluated.

Protected methods

void dump(FileDescriptor fd, PrintWriter fout, String[] args)

Performs a dump of the InputMethodService's internal state.

void onCurrentInputMethodSubtypeChanged(InputMethodSubtype newSubtype)

Called when the subtype was changed.

Inherited methods

void dump(FileDescriptor fd, PrintWriter fout, String[] args)

Implement this to handle Binder.dump() calls on your input method.

KeyEvent.DispatcherState getKeyDispatcherState()

Return the global KeyEvent.DispatcherState for used for processing events from the target application.

Object getSystemService(String name)

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

final IBinder onBind(Intent intent)

Return the communication channel to the service.

void onConfigurationChanged(Configuration configuration)

Called by the system when the device configuration changes while your component is running.

abstract AbstractInputMethodService.AbstractInputMethodImpl onCreateInputMethodInterface()

Called by the framework during initialization, when the InputMethod interface for this service needs to be created.

abstract AbstractInputMethodService.AbstractInputMethodSessionImpl onCreateInputMethodSessionInterface()

Called by the framework when a new InputMethodSession interface is needed for a new client of the input method.

void onDestroy()

Called by the system to notify a Service that it is no longer used and is being removed. If you override this method you must call through to the superclass implementation.

boolean onGenericMotionEvent(MotionEvent event)

Implement this to handle generic motion events on your input method.

void onLowMemory()

Override Service's empty implementation and listen to ActivityThread for low memory and trim memory events.

boolean onShouldVerifyKeyEvent(KeyEvent event)
boolean onTrackballEvent(MotionEvent event)

Implement this to handle trackball events on your input method.

void onTrimMemory(int level)

Called when the operating system has determined that it is a good time for a process to trim unneeded memory from its process.

void registerComponentCallbacks(ComponentCallbacks callback)

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.

void unregisterComponentCallbacks(ComponentCallbacks callback)

Remove a ComponentCallbacks object that was previously registered with registerComponentCallbacks(android.content.ComponentCallbacks).

void attachBaseContext(Context newBase)

Set the base context for this ContextWrapper.

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

Print the Service's state into the given stream.

final Application getApplication()

Return the application that owns this service.

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

abstract IBinder onBind(Intent intent)

Return the communication channel to the service.

void onConfigurationChanged(Configuration newConfig)

Called by the system when the device configuration changes while your component is running.

void onCreate()

Called by the system when the service is first created.

void onDestroy()

Called by the system to notify a Service that it is no longer used and is being removed.

void onLowMemory()

This is called when the overall system is running low on memory, and actively running processes should trim their memory usage.

void 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(Intent).

void onStart(Intent intent, int startId)

This method was deprecated in API level 15. Implement onStartCommand(android.content.Intent, int, int) instead.

int onStartCommand(Intent intent, int flags, int startId)

Called by the system every time a client explicitly starts the service by calling Context.startService(Intent), providing the arguments it supplied and a unique integer token representing the start request.

void onTaskRemoved(Intent rootIntent)

This is called if the service is currently running and the user has removed a task that comes from the service's application.

void onTimeout(int startId, int fgsType)

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

void onTimeout(int startId)

Callback called on timeout for ServiceInfo.FOREGROUND_SERVICE_TYPE_SHORT_SERVICE.

void onTrimMemory(int level)

Called when the operating system has determined that it is a good time for a process to trim unneeded memory from its process.

boolean onUnbind(Intent intent)

Called when all clients have disconnected from a particular interface published by the service.

final void startForeground(int id, 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.

final void startForeground(int id, Notification notification, int foregroundServiceType)

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

final void stopForeground(int notificationBehavior)

Remove this service from foreground state, allowing it to be killed if more memory is needed.

final void stopForeground(boolean removeNotification)

This method was deprecated in API level 33. call stopForeground(int) and pass either STOP_FOREGROUND_REMOVE or STOP_FOREGROUND_DETACH explicitly instead.

final void stopSelf()

Stop the service, if it was previously started.

final void stopSelf(int startId)

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

final boolean stopSelfResult(int startId)

Stop the service if the most recent time it was started was startId.

void attachBaseContext(Context base)

Set the base context for this ContextWrapper.

boolean bindIsolatedService(Intent service, int flags, String instanceName, Executor executor, ServiceConnection conn)

Variation of bindService(Intent, BindServiceFlags, Executor, ServiceConnection) that, in the specific case of isolated services, allows the caller to generate multiple instances of a service from a single component declaration.

boolean bindService(Intent service, int flags, Executor executor, ServiceConnection conn)

Same as bindService(Intent, ServiceConnection, int) with executor to control ServiceConnection callbacks.

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

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

boolean bindService(Intent service, ServiceConnection conn, int flags)

Connects to an application service, creating it if needed.

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

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

int checkCallingOrSelfPermission(String permission)

Determine whether the calling process of an IPC or you have been granted a particular permission.

int checkCallingOrSelfUriPermission(Uri uri, int modeFlags)

Determine whether the calling process of an IPC or you has been granted permission to access a specific URI.

int[] checkCallingOrSelfUriPermissions(List<Uri> uris, int modeFlags)

Determine whether the calling process of an IPC or you has been granted permission to access a list of URIs.

int checkCallingPermission(String permission)

Determine whether the calling process of an IPC you are handling has been granted a particular permission.

int checkCallingUriPermission(Uri uri, int modeFlags)

Determine whether the calling process and uid has been granted permission to access a specific URI.

int[] checkCallingUriPermissions(List<Uri> uris, int modeFlags)

Determine whether the calling process and uid has been granted permission to access a list of URIs.

int checkContentUriPermissionFull(Uri uri, int pid, int uid, int modeFlags)

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

int checkPermission(String permission, int pid, int uid)

Determine whether the given permission is allowed for a particular process and user ID running in the system.

int checkSelfPermission(String permission)

Determine whether you have been granted a particular permission.

int checkUriPermission(Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags)

Check both a Uri and normal permission.

int checkUriPermission(Uri uri, int pid, int uid, int modeFlags)

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

int[] checkUriPermissions(List<Uri> uris, int pid, int uid, int modeFlags)

Determine whether a particular process and uid has been granted permission to access a list of URIs.

void clearWallpaper()

This method is deprecated. Use WallpaperManager.clear() instead.

This method requires the caller to hold the permission Manifest.permission.SET_WALLPAPER.

Context createAttributionContext(String attributionTag)

Return a new Context object for the current Context but attribute to a different tag.

Context createConfigurationContext(Configuration overrideConfiguration)

Return a new Context object for the current Context but whose resources are adjusted to match the given Configuration.

Context createContext(ContextParams contextParams)

Creates a context with specific properties and behaviors.

Context createDeviceContext(int deviceId)

Returns a new Context object from the current context but with device association given by the deviceId.

Context createDeviceProtectedStorageContext()

Return a new Context object for the current Context but whose storage APIs are backed by device-protected storage.

Context createDisplayContext(Display display)

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

Context createPackageContext(String packageName, int flags)

Return a new Context object for the given application name.

Context createWindowContext(int type, Bundle options)

Creates a Context for a non-activity window.

Context createWindowContext(Display display, int type, Bundle options)

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

String[] databaseList()

Returns an array of strings naming the private databases associated with this Context's application package.

boolean deleteDatabase(String name)

Delete an existing private SQLiteDatabase associated with this Context's application package.

boolean deleteFile(String name)

Delete the given private file associated with this Context's application package.

boolean deleteSharedPreferences(String name)

Delete an existing shared preferences file.

void enforceCallingOrSelfPermission(String permission, String message)

If neither you nor the calling process of an IPC you are handling has been granted a particular permission, throw a SecurityException.

void enforceCallingOrSelfUriPermission(Uri uri, int modeFlags, String message)

If the calling process of an IPC or you has not been granted permission to access a specific URI, throw SecurityException.

void enforceCallingPermission(String permission, String message)

If the calling process of an IPC you are handling has not been granted a particular permission, throw a SecurityException.

void enforceCallingUriPermission(Uri uri, int modeFlags, String message)

If the calling process and uid has not been granted permission to access a specific URI, throw SecurityException.

void enforcePermission(String permission, int pid, int uid, String message)

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

void enforceUriPermission(Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags, String message)

Enforce both a Uri and normal permission.

void enforceUriPermission(Uri uri, int pid, int uid, int modeFlags, String message)

If a particular process and uid has not been granted permission to access a specific URI, throw SecurityException.

String[] fileList()

Returns an array of strings naming the private files associated with this Context's application package.

Context getApplicationContext()

Return the context of the single, global Application object of the current process.

ApplicationInfo getApplicationInfo()

Return the full application info for this context's package.

AssetManager getAssets()

Returns an AssetManager instance for the application's package.

AttributionSource getAttributionSource()

Context getBaseContext()
File getCacheDir()

Returns the absolute path to the application specific cache directory on the filesystem.

ClassLoader getClassLoader()

Return a class loader you can use to retrieve classes in this package.

File getCodeCacheDir()

Returns the absolute path to the application specific cache directory on the filesystem designed for storing cached code.

ContentResolver getContentResolver()

Return a ContentResolver instance for your application's package.

File getDataDir()

Returns the absolute path to the directory on the filesystem where all private files belonging to this app are stored.

File getDatabasePath(String name)

Returns the absolute path on the filesystem where a database created with openOrCreateDatabase(String, int, CursorFactory) is stored.

int getDeviceId()

Gets the device ID this context is associated with.

File getDir(String name, int mode)

Retrieve, creating if needed, a new directory in which the application can place its own custom data files.

Display getDisplay()

Get the display this context is associated with.

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.

File[] getExternalCacheDirs()

Returns absolute paths to application-specific directories on all shared/external storage devices where the application can place cache files it owns.

File getExternalFilesDir(String type)

Returns the absolute path to the directory on the primary shared/external storage device where the application can place persistent files it owns.

File[] getExternalFilesDirs(String type)

Returns absolute paths to application-specific directories on all shared/external storage devices where the application can place persistent files it owns.

File[] getExternalMediaDirs()

This method is deprecated. These directories still exist and are scanned, but developers are encouraged to migrate to inserting content into a MediaStore collection directly, as any app can contribute new media to MediaStore with no permissions required, starting in Build.VERSION_CODES.Q.

File getFileStreamPath(String name)

Returns the absolute path on the filesystem where a file created with openFileOutput(String, int) is stored.

File getFilesDir()

Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.

Executor getMainExecutor()

Return an Executor that will run enqueued tasks on the main thread associated with this context.

Looper getMainLooper()

Return the Looper for the main thread of the current process.

File getNoBackupFilesDir()

Returns the absolute path to the directory on the filesystem similar to getFilesDir().

File getObbDir()

Return the primary shared/external storage directory where this application's OBB files (if there are any) can be found.

File[] getObbDirs()

Returns absolute paths to application-specific directories on all shared/external storage devices where the application's OBB files (if there are any) can be found.

String getPackageCodePath()

Return the full path to this context's primary Android package.

PackageManager getPackageManager()

Return PackageManager instance to find global package information.

String getPackageName()

Return the name of this application's package.

String getPackageResourcePath()

Return the full path to this context's primary Android package.

ContextParams getParams()

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

Resources getResources()

Returns a Resources instance for the application's package.

SharedPreferences getSharedPreferences(String name, int mode)

Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values.

Object getSystemService(String name)

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

String getSystemServiceName(Class<?> serviceClass)

Gets the name of the system-level service that is represented by the specified class.

Resources.Theme getTheme()

Return the Theme object associated with this Context.

Drawable getWallpaper()

This method is deprecated. Use WallpaperManager.get() instead.

int getWallpaperDesiredMinimumHeight()

This method is deprecated. Use WallpaperManager.getDesiredMinimumHeight() instead.

int getWallpaperDesiredMinimumWidth()

This method is deprecated. Use WallpaperManager.getDesiredMinimumWidth() instead.

void grantUriPermission(String toPackage, Uri uri, int modeFlags)

Grant permission to access a specific Uri to another package, regardless of whether that package has general permission to access the Uri's content provider.

boolean isDeviceProtectedStorage()

Indicates if the storage APIs of this Context are backed by device-protected storage.

boolean isRestricted()

Indicates whether this Context is restricted.

boolean moveDatabaseFrom(Context sourceContext, String name)

Move an existing database file from the given source storage context to this context.

boolean moveSharedPreferencesFrom(Context sourceContext, String name)

Move an existing shared preferences file from the given source storage context to this context.

FileInputStream openFileInput(String name)

Open a private file associated with this Context's application package for reading.

FileOutputStream openFileOutput(String name, int mode)

Open a private file associated with this Context's application package for writing.

SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler)

Open a new private SQLiteDatabase associated with this Context's application package.

SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory)

Open a new private SQLiteDatabase associated with this Context's application package.

Drawable peekWallpaper()

This method is deprecated. Use WallpaperManager.peek() instead.

void registerComponentCallbacks(ComponentCallbacks callback)

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.

void registerDeviceIdChangeListener(Executor executor, IntConsumer listener)

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

Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter)

Register a BroadcastReceiver to be run in the main activity thread.

Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, int flags)

Register to receive intent broadcasts, with the receiver optionally being exposed to Instant Apps.

Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler, int flags)

Register to receive intent broadcasts, to run in the context of scheduler.

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

Register to receive intent broadcasts, to run in the context of scheduler.

void removeStickyBroadcast(Intent intent)

This method is deprecated. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.

void removeStickyBroadcastAsUser(Intent intent, UserHandle user)

This method is deprecated. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.

void revokeSelfPermissionsOnKill(Collection<String> permissions)

Triggers the revocation of one or more permissions for the calling package.

void revokeUriPermission(Uri uri, int modeFlags)

Remove all permissions to access a particular content provider Uri that were previously added with grantUriPermission(String, Uri, int) or any other mechanism.

void revokeUriPermission(String targetPackage, Uri uri, int modeFlags)

Remove permissions to access a particular content provider Uri that were previously added with grantUriPermission(String, Uri, int) for a specific target package.

void sendBroadcast(Intent intent, String receiverPermission, Bundle options)

Broadcast the given intent to all interested BroadcastReceivers, allowing an optional required permission to be enforced.

void sendBroadcast(Intent intent, String receiverPermission)

Broadcast the given intent to all interested BroadcastReceivers, allowing an optional required permission to be enforced.

void sendBroadcast(Intent intent)

Broadcast the given intent to all interested BroadcastReceivers.

void sendBroadcastAsUser(Intent intent, UserHandle user)

Version of sendBroadcast(android.content.Intent) that allows you to specify the user the broadcast will be sent to.

void sendBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission)

Version of sendBroadcast(android.content.Intent, java.lang.String) that allows you to specify the user the broadcast will be sent to.

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

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.

void sendOrderedBroadcast(Intent intent, int initialCode, String receiverPermission, String receiverAppOp, BroadcastReceiver resultReceiver, Handler scheduler, String initialData, Bundle initialExtras, Bundle options)

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

Version of sendBroadcast(android.content.Intent) that allows you to receive data back from the broadcast.

void sendOrderedBroadcast(Intent intent, String receiverPermission, Bundle options)

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.

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

Version of sendBroadcast(android.content.Intent) that allows you to receive data back from the broadcast.

void sendOrderedBroadcast(Intent intent, String receiverPermission)

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.

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

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.

void sendStickyBroadcast(Intent intent)

This method is deprecated. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.

void sendStickyBroadcast(Intent intent, Bundle options)

This method is deprecated. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.

void sendStickyBroadcastAsUser(Intent intent, UserHandle user)

This method is deprecated. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.

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

This method is deprecated. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.

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

This method is deprecated. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.

void setTheme(int resid)

Set the base theme for this context.

void setWallpaper(Bitmap bitmap)

This method is deprecated. Use WallpaperManager.set() instead.

This method requires the caller to hold the permission Manifest.permission.SET_WALLPAPER.

void setWallpaper(InputStream data)

This method is deprecated. Use WallpaperManager.set() instead.

This method requires the caller to hold the permission Manifest.permission.SET_WALLPAPER.

void startActivities(Intent[] intents, Bundle options)

Launch multiple new activities.

void startActivities(Intent[] intents)

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

void startActivity(Intent intent)

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

void startActivity(Intent intent, Bundle options)

Launch a new activity.

ComponentName startForegroundService(Intent service)

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.

boolean startInstrumentation(ComponentName className, String profileFile, Bundle arguments)

Start executing an Instrumentation class.

void startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)

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

void startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options)

Like startActivity(android.content.Intent, android.os.Bundle), but taking a IntentSender to start.

ComponentName startService(Intent service)

Request that a given application service be started.

boolean stopService(Intent name)

Request that a given application service be stopped.

void unbindService(ServiceConnection conn)

Disconnect from an application service.

void unregisterComponentCallbacks(ComponentCallbacks callback)

Remove a ComponentCallbacks object that was previously registered with registerComponentCallbacks(android.content.ComponentCallbacks).

void unregisterDeviceIdChangeListener(IntConsumer listener)

Removes a device ID changed listener from the Context.

void unregisterReceiver(BroadcastReceiver receiver)

Unregister a previously registered BroadcastReceiver.

void updateServiceGroup(ServiceConnection conn, int group, int importance)

For a service previously bound with bindService(Intent, BindServiceFlags, Executor, ServiceConnection) or a related method, change how the system manages that service's process in relation to other processes.

boolean bindIsolatedService(Intent service, int flags, String instanceName, Executor executor, ServiceConnection conn)

Variation of bindService(Intent, BindServiceFlags, Executor, ServiceConnection) that, in the specific case of isolated services, allows the caller to generate multiple instances of a service from a single component declaration.

boolean bindIsolatedService(Intent service, Context.BindServiceFlags flags, String instanceName, Executor executor, ServiceConnection conn)

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.

boolean bindService(Intent service, int flags, Executor executor, ServiceConnection conn)

Same as bindService(Intent, ServiceConnection, int) with executor to control ServiceConnection callbacks.

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

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

abstract boolean bindService(Intent service, ServiceConnection conn, int flags)

Connects to an application service, creating it if needed.

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

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

boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags, UserHandle user)

Binds to a service in the given user in the same manner as bindService(Intent, BindServiceFlags, Executor, ServiceConnection).

boolean bindServiceAsUser(Intent service, ServiceConnection conn, Context.BindServiceFlags flags, UserHandle user)

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

abstract int checkCallingOrSelfPermission(String permission)

Determine whether the calling process of an IPC or you have been granted a particular permission.

abstract int checkCallingOrSelfUriPermission(Uri uri, int modeFlags)

Determine whether the calling process of an IPC or you has been granted permission to access a specific URI.

int[] checkCallingOrSelfUriPermissions(List<Uri> uris, int modeFlags)

Determine whether the calling process of an IPC or you has been granted permission to access a list of URIs.

abstract int checkCallingPermission(String permission)

Determine whether the calling process of an IPC you are handling has been granted a particular permission.

abstract int checkCallingUriPermission(Uri uri, int modeFlags)

Determine whether the calling process and uid has been granted permission to access a specific URI.

int[] checkCallingUriPermissions(List<Uri> uris, int modeFlags)

Determine whether the calling process and uid has been granted permission to access a list of URIs.

int checkContentUriPermissionFull(Uri uri, int pid, int uid, int modeFlags)

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

abstract int checkPermission(String permission, int pid, int uid)

Determine whether the given permission is allowed for a particular process and user ID running in the system.

abstract int checkSelfPermission(String permission)

Determine whether you have been granted a particular permission.

abstract int checkUriPermission(Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags)

Check both a Uri and normal permission.

abstract int checkUriPermission(Uri uri, int pid, int uid, int modeFlags)

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

int[] checkUriPermissions(List<Uri> uris, int pid, int uid, int modeFlags)

Determine whether a particular process and uid has been granted permission to access a list of URIs.

abstract void clearWallpaper()

This method was deprecated in API level 15. Use WallpaperManager.clear() instead.

This method requires the caller to hold the permission Manifest.permission.SET_WALLPAPER.

Context createAttributionContext(String attributionTag)

Return a new Context object for the current Context but attribute to a different tag.

abstract Context createConfigurationContext(Configuration overrideConfiguration)

Return a new Context object for the current Context but whose resources are adjusted to match the given Configuration.

Context createContext(ContextParams contextParams)

Creates a context with specific properties and behaviors.

abstract Context createContextForSplit(String splitName)

Return a new Context object for the given split name.

Context createDeviceContext(int deviceId)

Returns a new Context object from the current context but with device association given by the deviceId.

abstract Context createDeviceProtectedStorageContext()

Return a new Context object for the current Context but whose storage APIs are backed by device-protected storage.

abstract Context createDisplayContext(Display display)

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

abstract Context createPackageContext(String packageName, int flags)

Return a new Context object for the given application name.

Context createWindowContext(int type, Bundle options)

Creates a Context for a non-activity window.

Context createWindowContext(Display display, int type, Bundle options)

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

abstract String[] databaseList()

Returns an array of strings naming the private databases associated with this Context's application package.

abstract boolean deleteDatabase(String name)

Delete an existing private SQLiteDatabase associated with this Context's application package.

abstract boolean deleteFile(String name)

Delete the given private file associated with this Context's application package.

abstract boolean deleteSharedPreferences(String name)

Delete an existing shared preferences file.

abstract void enforceCallingOrSelfPermission(String permission, String message)

If neither you nor the calling process of an IPC you are handling has been granted a particular permission, throw a SecurityException.

abstract void enforceCallingOrSelfUriPermission(Uri uri, int modeFlags, String message)

If the calling process of an IPC or you has not been granted permission to access a specific URI, throw SecurityException.

abstract void enforceCallingPermission(String permission, String message)

If the calling process of an IPC you are handling has not been granted a particular permission, throw a SecurityException.

abstract void enforceCallingUriPermission(Uri uri, int modeFlags, String message)

If the calling process and uid has not been granted permission to access a specific URI, throw SecurityException.

abstract void enforcePermission(String permission, int pid, int uid, String message)

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

abstract void enforceUriPermission(Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags, String message)

Enforce both a Uri and normal permission.

abstract void enforceUriPermission(Uri uri, int pid, int uid, int modeFlags, String message)

If a particular process and uid has not been granted permission to access a specific URI, throw SecurityException.

abstract String[] fileList()

Returns an array of strings naming the private files associated with this Context's application package.

abstract Context getApplicationContext()

Return the context of the single, global Application object of the current process.

abstract ApplicationInfo getApplicationInfo()

Return the full application info for this context's package.

abstract AssetManager getAssets()

Returns an AssetManager instance for the application's package.

AttributionSource getAttributionSource()
String getAttributionTag()

Attribution can be used in complex apps to logically separate parts of the app.

abstract File getCacheDir()

Returns the absolute path to the application specific cache directory on the filesystem.

abstract ClassLoader getClassLoader()

Return a class loader you can use to retrieve classes in this package.

abstract File getCodeCacheDir()

Returns the absolute path to the application specific cache directory on the filesystem designed for storing cached code.

final int getColor(int id)

Returns a color associated with a particular resource ID and styled for the current theme.

final ColorStateList getColorStateList(int id)

Returns a color state list associated with a particular resource ID and styled for the current theme.

abstract ContentResolver getContentResolver()

Return a ContentResolver instance for your application's package.

abstract File getDataDir()

Returns the absolute path to the directory on the filesystem where all private files belonging to this app are stored.

abstract File getDatabasePath(String name)

Returns the absolute path on the filesystem where a database created with openOrCreateDatabase(String, int, CursorFactory) is stored.

int getDeviceId()

Gets the device ID this context is associated with.

abstract File getDir(String name, int mode)

Retrieve, creating if needed, a new directory in which the application can place its own custom data files.

Display getDisplay()

Get the display this context is associated with.

final Drawable getDrawable(int id)

Returns a drawable object associated with a particular resource ID and styled for the current theme.

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

abstract File[] getExternalCacheDirs()

Returns absolute paths to application-specific directories on all shared/external storage devices where the application can place cache files it owns.

abstract File getExternalFilesDir(String type)

Returns the absolute path to the directory on the primary shared/external storage device where the application can place persistent files it owns.

abstract File[] getExternalFilesDirs(String type)

Returns absolute paths to application-specific directories on all shared/external storage devices where the application can place persistent files it owns.

abstract File[] getExternalMediaDirs()

This method was deprecated in API level 30. These directories still exist and are scanned, but developers are encouraged to migrate to inserting content into a MediaStore collection directly, as any app can contribute new media to MediaStore with no permissions required, starting in Build.VERSION_CODES.Q.

abstract File getFileStreamPath(String name)

Returns the absolute path on the filesystem where a file created with openFileOutput(String, int) is stored.

abstract File getFilesDir()

Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.

Executor getMainExecutor()

Return an Executor that will run enqueued tasks on the main thread associated with this context.

abstract Looper getMainLooper()

Return the Looper for the main thread of the current process.

abstract File getNoBackupFilesDir()

Returns the absolute path to the directory on the filesystem similar to getFilesDir().

abstract File getObbDir()

Return the primary shared/external storage directory where this application's OBB files (if there are any) can be found.

abstract File[] getObbDirs()

Returns absolute paths to application-specific directories on all shared/external storage devices where the application's OBB files (if there are any) can be found.

String getOpPackageName()

Return the package name that should be used for AppOpsManager calls from this context, so that app ops manager's uid verification will work with the name.

abstract String getPackageCodePath()

Return the full path to this context's primary Android package.

abstract PackageManager getPackageManager()

Return PackageManager instance to find global package information.

abstract String getPackageName()

Return the name of this application's package.

abstract String getPackageResourcePath()

Return the full path to this context's primary Android package.

ContextParams getParams()

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

abstract Resources getResources()

Returns a Resources instance for the application's package.

abstract SharedPreferences getSharedPreferences(String name, int mode)

Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values.

final String getString(int resId)

Returns a localized string from the application's package's default string table.

final String getString(int resId, Object... formatArgs)

Returns a localized formatted string from the application's package's default string table, substituting the format arguments as defined in Formatter and String.format(String, Object).

final <T> T getSystemService(Class<T> serviceClass)

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

abstract Object getSystemService(String name)

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

abstract String getSystemServiceName(Class<?> serviceClass)

Gets the name of the system-level service that is represented by the specified class.

final CharSequence getText(int resId)

Return a localized, styled CharSequence from the application's package's default string table.

abstract Resources.Theme getTheme()

Return the Theme object associated with this Context.

abstract Drawable getWallpaper()

This method was deprecated in API level 15. Use WallpaperManager.get() instead.

abstract int getWallpaperDesiredMinimumHeight()

This method was deprecated in API level 15. Use WallpaperManager.getDesiredMinimumHeight() instead.

abstract int getWallpaperDesiredMinimumWidth()

This method was deprecated in API level 15. Use WallpaperManager.getDesiredMinimumWidth() instead.

abstract void grantUriPermission(String toPackage, Uri uri, int modeFlags)

Grant permission to access a specific Uri to another package, regardless of whether that package has general permission to access the Uri's content provider.

abstract boolean isDeviceProtectedStorage()

Indicates if the storage APIs of this Context are backed by device-protected storage.

boolean isRestricted()

Indicates whether this Context is restricted.

boolean isUiContext()

Returns true if the context is a UI context which can access UI components such as WindowManager, LayoutInflater or WallpaperManager.

abstract boolean moveDatabaseFrom(Context sourceContext, String name)

Move an existing database file from the given source storage context to this context.

abstract boolean moveSharedPreferencesFrom(Context sourceContext, String name)

Move an existing shared preferences file from the given source storage context to this context.

final TypedArray obtainStyledAttributes(AttributeSet set, int[] attrs)

Retrieve styled attribute information in this Context's theme.

final TypedArray obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)

Retrieve styled attribute information in this Context's theme.

final TypedArray obtainStyledAttributes(int resid, int[] attrs)

Retrieve styled attribute information in this Context's theme.

final TypedArray obtainStyledAttributes(int[] attrs)

Retrieve styled attribute information in this Context's theme.

abstract FileInputStream openFileInput(String name)

Open a private file associated with this Context's application package for reading.

abstract FileOutputStream openFileOutput(String name, int mode)

Open a private file associated with this Context's application package for writing.

abstract SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler)

Open a new private SQLiteDatabase associated with this Context's application package.

abstract SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory)

Open a new private SQLiteDatabase associated with this Context's application package.

abstract Drawable peekWallpaper()

This method was deprecated in API level 15. Use WallpaperManager.peek() instead.

void registerComponentCallbacks(ComponentCallbacks callback)

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.

void registerDeviceIdChangeListener(Executor executor, IntConsumer listener)

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

abstract Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter)

Register a BroadcastReceiver to be run in the main activity thread.

abstract Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, int flags)

Register to receive intent broadcasts, with the receiver optionally being exposed to Instant Apps.

abstract Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler, int flags)

Register to receive intent broadcasts, to run in the context of scheduler.

abstract Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)

Register to receive intent broadcasts, to run in the context of scheduler.

abstract void removeStickyBroadcast(Intent intent)

This method was deprecated in API level 21. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.

abstract void removeStickyBroadcastAsUser(Intent intent, UserHandle user)

This method was deprecated in API level 21. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.

void revokeSelfPermissionOnKill(String permName)

Triggers the asynchronous revocation of a runtime permission.

void revokeSelfPermissionsOnKill(Collection<String> permissions)

Triggers the revocation of one or more permissions for the calling package.

abstract void revokeUriPermission(Uri uri, int modeFlags)

Remove all permissions to access a particular content provider Uri that were previously added with grantUriPermission(String, Uri, int) or any other mechanism.

abstract void revokeUriPermission(String toPackage, Uri uri, int modeFlags)

Remove permissions to access a particular content provider Uri that were previously added with grantUriPermission(String, Uri, int) for a specific target package.

void sendBroadcast(Intent intent, String receiverPermission, Bundle options)

Broadcast the given intent to all interested BroadcastReceivers, allowing an optional required permission to be enforced.

abstract void sendBroadcast(Intent intent, String receiverPermission)

Broadcast the given intent to all interested BroadcastReceivers, allowing an optional required permission to be enforced.

abstract void sendBroadcast(Intent intent)

Broadcast the given intent to all interested BroadcastReceivers.

abstract void sendBroadcastAsUser(Intent intent, UserHandle user)

Version of sendBroadcast(android.content.Intent) that allows you to specify the user the broadcast will be sent to.

abstract void sendBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission)

Version of sendBroadcast(android.content.Intent, java.lang.String) that allows you to specify the user the broadcast will be sent to.

void sendBroadcastWithMultiplePermissions(Intent intent, String[] receiverPermissions)

Broadcast the given intent to all interested BroadcastReceivers, allowing an array of required permissions to be enforced.

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

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.

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

Version of sendBroadcast(android.content.Intent) that allows you to receive data back from the broadcast.

void sendOrderedBroadcast(Intent intent, String receiverPermission, Bundle options)

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.

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

Version of sendBroadcast(android.content.Intent) that allows you to receive data back from the broadcast.

abstract void sendOrderedBroadcast(Intent intent, String receiverPermission)

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.

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

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.

abstract void sendStickyBroadcast(Intent intent)

This method was deprecated in API level 21. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.

void sendStickyBroadcast(Intent intent, Bundle options)

This method was deprecated in API level 31. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.

abstract void sendStickyBroadcastAsUser(Intent intent, UserHandle user)

This method was deprecated in API level 21. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.

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

This method was deprecated in API level 21. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.

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

This method was deprecated in API level 21. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.

abstract void setTheme(int resid)

Set the base theme for this context.

abstract void setWallpaper(Bitmap bitmap)

This method was deprecated in API level 15. Use WallpaperManager.set() instead.

This method requires the caller to hold the permission Manifest.permission.SET_WALLPAPER.

abstract void setWallpaper(InputStream data)

This method was deprecated in API level 15. Use WallpaperManager.set() instead.

This method requires the caller to hold the permission Manifest.permission.SET_WALLPAPER.

abstract void startActivities(Intent[] intents, Bundle options)

Launch multiple new activities.

abstract void startActivities(Intent[] intents)

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

abstract void startActivity(Intent intent)

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

abstract void startActivity(Intent intent, Bundle options)

Launch a new activity.

abstract ComponentName startForegroundService(Intent service)

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.

abstract boolean startInstrumentation(ComponentName className, String profileFile, Bundle arguments)

Start executing an Instrumentation class.

abstract void startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)

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

abstract void startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options)

Like startActivity(android.content.Intent, android.os.Bundle), but taking a IntentSender to start.

abstract ComponentName startService(Intent service)

Request that a given application service be started.

abstract boolean stopService(Intent service)

Request that a given application service be stopped.

abstract void unbindService(ServiceConnection conn)

Disconnect from an application service.

void unregisterComponentCallbacks(ComponentCallbacks callback)

Remove a ComponentCallbacks object that was previously registered with registerComponentCallbacks(android.content.ComponentCallbacks).

void unregisterDeviceIdChangeListener(IntConsumer listener)

Removes a device ID changed listener from the Context.

abstract void unregisterReceiver(BroadcastReceiver receiver)

Unregister a previously registered BroadcastReceiver.

void updateServiceGroup(ServiceConnection conn, int group, int importance)

For a service previously bound with bindService(Intent, BindServiceFlags, Executor, ServiceConnection) or a related method, change how the system manages that service's process in relation to other processes.

Object clone()

Creates and returns a copy of this object.

boolean equals(Object obj)

Indicates whether some other object is "equal to" this one.

void finalize()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

final Class<?> getClass()

Returns the runtime class of this Object.

int hashCode()

Returns a hash code value for the object.

final void notify()

Wakes up a single thread that is waiting on this object's monitor.

final void notifyAll()

Wakes up all threads that are waiting on this object's monitor.

String toString()

Returns a string representation of the object.

final void wait(long timeoutMillis, int nanos)

Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.

final void wait(long timeoutMillis)

Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.

final void wait()

Causes the current thread to wait until it is awakened, typically by being notified or interrupted.

abstract boolean onKeyDown(int keyCode, KeyEvent event)

Called when a key down event has occurred.

abstract boolean onKeyLongPress(int keyCode, KeyEvent event)

Called when a long press has occurred.

abstract boolean onKeyMultiple(int keyCode, int count, KeyEvent event)

Called when a user's interaction with an analog control, such as flinging a trackball, generates simulated down/up events for the same key multiple times in quick succession.

abstract boolean onKeyUp(int keyCode, KeyEvent event)

Called when a key up event has occurred.

abstract void onTrimMemory(int level)

Called when the operating system has determined that it is a good time for a process to trim unneeded memory from its process.

abstract void onConfigurationChanged(Configuration newConfig)

Called by the system when the device configuration changes while your component is running.

abstract void onLowMemory()

This method was deprecated in API level 35. Since API level 14 this is superseded by ComponentCallbacks2.onTrimMemory. Since API level 34 this is never called. If you're overriding ComponentCallbacks2#onTrimMemory and your minSdkVersion is greater than API 14, you can provide an empty implementation for this method.

XML attributes

android:imeExtractEnterAnimation

Animation to use when showing the fullscreen extract UI after it had previously been hidden.

May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name".

android:imeExtractExitAnimation

Animation to use when hiding the fullscreen extract UI after it had previously been shown.

May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name".

android:imeFullscreenBackground

Background to use for entire input method when it is being shown in fullscreen mode with the extract view, to ensure that it completely covers the application. This allows, for example, the candidate view to be hidden while in fullscreen mode without having the application show through behind it.

May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name".

May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

Constants

BACK_DISPOSITION_ADJUST_NOTHING

Added in API level 28
public static final int BACK_DISPOSITION_ADJUST_NOTHING

Asks the system to not adjust the back button affordance even when the software keyboard is shown.

This mode is useful for UI modes where IME's main soft input window is used for some supplemental UI, such as floating candidate window for languages such as Chinese and Japanese, where users expect the back button is, or at least looks to be, handled by the target application rather than the UI shown by the IME even while isInputViewShown() returns true.

Note that KeyEvent.KEYCODE_BACK events continue to be sent to onKeyDown(int, android.view.KeyEvent) even when this mode is specified. The default implementation of onKeyDown(int, android.view.KeyEvent) for KeyEvent.KEYCODE_BACK does not take this mode into account.

Constant Value: 3 (0x00000003)

BACK_DISPOSITION_DEFAULT

Added in API level 11
public static final int BACK_DISPOSITION_DEFAULT

Allows the system to optimize the back button affordance based on the presence of software keyboard.

For instance, on devices that have navigation bar and software-rendered back button, the system may use a different icon while isInputViewShown() returns true, to indicate that the back button has "dismiss" affordance.

Note that KeyEvent.KEYCODE_BACK events continue to be sent to onKeyDown(int, android.view.KeyEvent) even when this mode is specified. The default implementation of onKeyDown(int, android.view.KeyEvent) for KeyEvent.KEYCODE_BACK does not take this mode into account.

For API level Build.VERSION_CODES.O_MR1 and lower devices, this is the only mode you can safely specify without worrying about the compatibility.

Constant Value: 0 (0x00000000)

BACK_DISPOSITION_WILL_DISMISS

Added in API level 11
Deprecated in API level 28
public static final int BACK_DISPOSITION_WILL_DISMISS

This constant was deprecated in API level 28.
on Build.VERSION_CODES.P and later devices, this flag is handled as a synonym of BACK_DISPOSITION_DEFAULT. On Build.VERSION_CODES.O_MR1 and prior devices, expected behavior of this mode had not been well defined. In AOSP implementation running on devices that have navigation bar, specifying this flag could change the software back button to "Dismiss" icon no matter whether the software keyboard is shown or not, but there would be no easy way to restore the icon state even after IME lost the connection to the application. To avoid user confusions, do not specify this mode anyway

Deprecated flag.

To avoid compatibility issues, IME developers should not use this flag.

Constant Value: 2 (0x00000002)

BACK_DISPOSITION_WILL_NOT_DISMISS

Added in API level 11
Deprecated in API level 28
public static final int BACK_DISPOSITION_WILL_NOT_DISMISS

This constant was deprecated in API level 28.
on Build.VERSION_CODES.P and later devices, this flag is handled as a synonym of BACK_DISPOSITION_DEFAULT. On Build.VERSION_CODES.O_MR1 and prior devices, expected behavior of this mode had not been well defined. Most likely the end result would be the same as BACK_DISPOSITION_DEFAULT. Either way it is not recommended to use this mode

Deprecated flag.

To avoid compatibility issues, IME developers should not use this flag.

Constant Value: 1 (0x00000001)

Public constructors

InputMethodService

public InputMethodService ()

Public methods

enableHardwareAcceleration

Added in API level 17
Deprecated in API level 21
public boolean enableHardwareAcceleration ()

This method was deprecated in API level 21.
Starting in API 21, hardware acceleration is always enabled on capable devices

You can call this to try to enable accelerated drawing for your IME. This must be set before onCreate(), so you will typically call it in your constructor. It is not always possible to use hardware accelerated drawing in an IME (for example on low-end devices that do not have the resources to support this), so the call true if it succeeds otherwise false if you will need to draw in software. You must be able to handle either case.

In API 21 and later, system may automatically enable hardware accelerated drawing for your IME on capable devices even if this method is not explicitly called. Make sure that your IME is able to handle either case.

Returns
boolean true if accelerated drawing is successfully enabled otherwise false. On API 21 and later devices the return value is basically just a hint and your IME does not need to change the behavior based on the it

finishConnectionlessStylusHandwriting

Added in API level 35
public final void finishConnectionlessStylusHandwriting (CharSequence text)

Finishes the current connectionless stylus handwriting session and delivers the result.

This dismisses the ink window and stops intercepting stylus MotionEvents.

Note for IME developers: Call this method at any time to finish the current handwriting session. Generally, this should be invoked after a short timeout, giving the user enough time to start the next stylus stroke, if any. By default, system will time-out after few seconds. To override default timeout, use setStylusHandwritingSessionTimeout(java.time.Duration).

Parameters
text CharSequence: This value may be null.

finishStylusHandwriting

Added in API level 33
public final void finishStylusHandwriting ()

Finish the current stylus handwriting session.

This dismisses the ink window and stops intercepting stylus MotionEvents.

Connectionless handwriting sessions should be finished using finishConnectionlessStylusHandwriting(java.lang.CharSequence).

Note for IME developers: Call this method at any time to finish the current handwriting session. Generally, this should be invoked after a short timeout, giving the user enough time to start the next stylus stroke, if any. By default, system will time-out after few seconds. To override default timeout, use setStylusHandwritingSessionTimeout(java.time.Duration).

Handwriting session will be finished by framework on next onFinishInput().

getBackDisposition

Added in API level 11
public int getBackDisposition ()

Retrieves the current disposition mode that indicates the expected back button affordance.

getCandidatesHiddenVisibility

Added in API level 3
public int getCandidatesHiddenVisibility ()

Returns the visibility mode (either View.INVISIBLE or View.GONE) of the candidates view when it is not shown. The default implementation returns GONE when isExtractViewShown() returns true, otherwise INVISIBLE. Be careful if you change this to return GONE in other situations -- if showing or hiding the candidates view causes your window to resize, this can cause temporary drawing artifacts as the resize takes place.

Returns
int

getCurrentInputBinding

Added in API level 3
public InputBinding getCurrentInputBinding ()

Return the currently active InputBinding for the input method, or null if there is none.

Returns
InputBinding

getCurrentInputConnection

Added in API level 3
public InputConnection getCurrentInputConnection ()

Retrieve the currently active InputConnection that is bound to the input method, or null if there is none.

Returns
InputConnection

getCurrentInputEditorInfo

Added in API level 3
public EditorInfo getCurrentInputEditorInfo ()

Returns
EditorInfo

getCurrentInputStarted

Added in API level 3
public boolean getCurrentInputStarted ()

Returns
boolean

getInputMethodWindowRecommendedHeight

Added in API level 21
Deprecated in API level 29
public int getInputMethodWindowRecommendedHeight ()

This method was deprecated in API level 29.
the actual behavior of this method has never been well defined. You cannot use this method in a reliable and predictable way

Aimed to return the previous input method's Insets.contentTopInsets, but its actual semantics has never been well defined.

Note that the previous document clearly mentioned that this method could return 0 at any time for whatever reason. Now this method is just always returning 0.

Returns
int on Android Build.VERSION_CODES.Q and later devices this method always returns 0

getLayoutInflater

Added in API level 3
public LayoutInflater getLayoutInflater ()

Returns
LayoutInflater

getMaxWidth

Added in API level 3
public int getMaxWidth ()

Return the maximum width, in pixels, available the input method. Input methods are positioned at the bottom of the screen and, unless running in fullscreen, will generally want to be as short as possible so should compute their height based on their contents. However, they can stretch as much as needed horizontally. The function returns to you the maximum amount of space available horizontally, which you can use if needed for UI placement.

In many cases this is not needed, you can just rely on the normal view layout mechanisms to position your views within the full horizontal space given to the input method.

Note that this value can change dynamically, in particular when the screen orientation changes.

Returns
int

getStylusHandwritingIdleTimeoutMax

Added in API level 34
public static final Duration getStylusHandwritingIdleTimeoutMax ()

Returns the maximum stylus handwriting session idle-timeout for use with setStylusHandwritingSessionTimeout(java.time.Duration).

Returns
Duration This value cannot be null.

getStylusHandwritingSessionTimeout

Added in API level 34
public final Duration getStylusHandwritingSessionTimeout ()

Returns the duration after which an ongoing stylus handwriting session that hasn't received new MotionEvents will time out and finishStylusHandwriting() will be called. The current timeout can be changed using setStylusHandwritingSessionTimeout(java.time.Duration).

Returns
Duration This value cannot be null.

getStylusHandwritingWindow

Added in API level 33
public final Window getStylusHandwritingWindow ()

Returns the stylus handwriting inking window. IMEs supporting stylus input are expected to attach their inking views to this window (e.g. with Window.setContentView(View) )). Handwriting-related MotionEvents are dispatched to the attached view hierarchy. Note: This returns null if IME doesn't support stylus handwriting i.e. if InputMethodInfo.supportsStylusHandwriting() is false. This method should be called after onStartStylusHandwriting().

Returns
Window

getSystemService

Added in API level 3
public Object getSystemService (String name)

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 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 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 ActivityManager for interacting with the global activity state of the system.
WALLPAPER_SERVICE ("wallpaper")
A 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 PowerManager for controlling power management.
ALARM_SERVICE ("alarm")
A AlarmManager for receiving intents at the time of your choosing.
NOTIFICATION_SERVICE ("notification")
A NotificationManager for informing the user of background events.
KEYGUARD_SERVICE ("keyguard")
A KeyguardManager for controlling keyguard.
LOCATION_SERVICE ("location")
A LocationManager for controlling location (e.g., GPS) updates.
SEARCH_SERVICE ("search")
A SearchManager for handling search.
VIBRATOR_MANAGER_SERVICE ("vibrator_manager")
A VibratorManager for accessing the device vibrators, interacting with individual ones and playing synchronized effects on multiple vibrators.
VIBRATOR_SERVICE ("vibrator")
A 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 UiModeManager for controlling UI modes.
DOWNLOAD_SERVICE ("download")
A DownloadManager for requesting HTTP downloads
BATTERY_SERVICE ("batterymanager")
A BatteryManager for managing battery state
JOB_SCHEDULER_SERVICE ("taskmanager")
A JobScheduler for managing scheduled tasks
NETWORK_STATS_SERVICE ("netstats")
A NetworkStatsManager for querying network usage statistics.
HARDWARE_PROPERTIES_SERVICE ("hardware_properties")
A HardwarePropertiesManager for accessing hardware properties.
DOMAIN_VERIFICATION_SERVICE ("domain_verification")
A DomainVerificationManager for accessing web domain approval state.
DISPLAY_HASH_SERVICE ("display_hash")
A DisplayHashManager for management of display hashes.
ERROR(/#AUTHENTICATION_POLICY_SERVICE) ("authentication_policy")
A ERROR(/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: This value cannot be null.

Returns
Object This value may be null.

getTextForImeAction

Added in API level 3
public CharSequence getTextForImeAction (int imeOptions)

Return text that can be used as a button label for the given EditorInfo.imeOptions. Returns null if there is no action requested. Note that there is no guarantee that the returned text will be relatively short, so you probably do not want to use it as text on a soft keyboard key label.

Parameters
imeOptions int: The value from EditorInfo.imeOptions.

Returns
CharSequence Returns a label to use, or null if there is no action.

getWindow

Added in API level 3
public Dialog getWindow ()

Returns
Dialog

hideStatusIcon

Added in API level 3
public void hideStatusIcon ()

hideWindow

Added in API level 3
public void hideWindow ()

isExtractViewShown

Added in API level 3
public boolean isExtractViewShown ()

Return whether the fullscreen extract view is shown. This will only return true if isFullscreenMode() returns true, and in that case its value depends on the last call to setExtractViewShown(boolean). This effectively lets you determine if the application window is entirely covered (when this returns true) or if some part of it may be shown (if this returns false, though if isFullscreenMode() returns true in that case then it is probably only a sliver of the application).

Returns
boolean

isFullscreenMode

Added in API level 3
public boolean isFullscreenMode ()

Return whether the input method is currently running in fullscreen mode. This is the mode that was last determined and applied by updateFullscreenMode().

Returns
boolean

isInputViewShown

Added in API level 3
public boolean isInputViewShown ()

Return whether the soft input view is currently shown to the user. This is the state that was last determined and applied by updateInputViewShown().

Returns
boolean

isShowInputRequested

Added in API level 3
public boolean isShowInputRequested ()

Returns true if we have been asked to show our input view.

Returns
boolean

onAppPrivateCommand

Added in API level 3
public void onAppPrivateCommand (String action, 
                Bundle data)

Not implemented in this class.

Parameters
action String

data Bundle

onBindInput

Added in API level 3
public void onBindInput ()

Called when a new client has bound to the input method. This may be followed by a series of onStartInput(android.view.inputmethod.EditorInfo, boolean) and onFinishInput() calls as the user navigates through its UI. Upon this call you know that getCurrentInputBinding() and getCurrentInputConnection() return valid objects.

onComputeInsets

Added in API level 3
public void onComputeInsets (InputMethodService.Insets outInsets)

Compute the interesting insets into your UI. The default implementation uses the top of the candidates frame for the visible insets, and the top of the input frame for the content insets. The default touchable insets are Insets.TOUCHABLE_INSETS_VISIBLE.

Note that this method is not called when isExtractViewShown() returns true, since in that case the application is left as-is behind the input method and not impacted by anything in its UI.

Parameters
outInsets InputMethodService.Insets: Fill in with the current UI insets.

onConfigurationChanged

Added in API level 3
public void onConfigurationChanged (Configuration newConfig)

Take care of handling configuration changes. Subclasses of InputMethodService generally don't need to deal directly with this on their own; the standard implementation here takes care of regenerating the input method UI as a result of the configuration change, so you can rely on your onCreateInputView() and other methods being called as appropriate due to a configuration change.

When a configuration change does happen, onInitializeInterface() is guaranteed to be called the next time prior to any of the other input or UI creation callbacks. The following will be called immediately depending if appropriate for current state: onStartInput(EditorInfo, boolean) if input is active, and onCreateInputView() and onStartInputView(EditorInfo, boolean) and related appropriate functions if the UI is displayed.

Starting with Build.VERSION_CODES.S, IMEs can opt into handling configuration changes themselves instead of being restarted with R.styleable.InputMethod_configChanges.

Parameters
newConfig Configuration: This value cannot be null.

onConfigureWindow

Added in API level 3
public void onConfigureWindow (Window win, 
                boolean isFullscreen, 
                boolean isCandidatesOnly)

Update the given window's parameters for the given mode. This is called when the window is first displayed and each time the fullscreen or candidates only mode changes.

The default implementation makes the layout for the window MATCH_PARENT x MATCH_PARENT when in fullscreen mode, and MATCH_PARENT x WRAP_CONTENT when in non-fullscreen mode.

Parameters
win Window: The input method's window.

isFullscreen boolean: If true, the window is running in fullscreen mode and intended to cover the entire application display.

isCandidatesOnly boolean: If true, the window is only showing the candidates view and none of the rest of its UI. This is mutually exclusive with fullscreen mode.

onCreate

Added in API level 3
public void onCreate ()

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

onCreateCandidatesView

Added in API level 3
public View onCreateCandidatesView ()

Create and return the view hierarchy used to show candidates. This will be called once, when the candidates are first displayed. You can return null to have no candidates view; the default implementation returns null.

To control when the candidates view is displayed, use setCandidatesViewShown(boolean). To change the candidates view after the first one is created by this function, use setCandidatesView(android.view.View).

Returns
View

onCreateExtractTextView

Added in API level 3
public View onCreateExtractTextView ()

Called by the framework to create the layout for showing extracted text. Only called when in fullscreen mode. The returned view hierarchy must have an ExtractEditText whose ID is R.id.inputExtractEditText, with action ID R.id.inputExtractAction and accessories ID R.id.inputExtractAccessories.

Returns
View

onCreateInlineSuggestionsRequest

Added in API level 30
public InlineSuggestionsRequest onCreateInlineSuggestionsRequest (Bundle uiExtras)

Called when Autofill is requesting an InlineSuggestionsRequest from the IME.

The Autofill Framework will first request the IME to create and send an InlineSuggestionsRequest back. Once Autofill Framework receives a valid request and also receives valid inline suggestions, they will be returned via onInlineSuggestionsResponse(android.view.inputmethod.InlineSuggestionsResponse).

IME Lifecycle - The request will wait to be created after inputStarted

If the IME wants to support displaying inline suggestions, they must set supportsInlineSuggestions in its XML and implement this method to return a valid InlineSuggestionsRequest.

Parameters
uiExtras Bundle: the extras that contain the UI renderer related information This value cannot be null.

Returns
InlineSuggestionsRequest an InlineSuggestionsRequest to be sent to Autofill. This value may be null.

onCreateInputMethodInterface

Added in API level 3
public AbstractInputMethodService.AbstractInputMethodImpl onCreateInputMethodInterface ()

This method is deprecated.
Overriding or calling this method is strongly discouraged. A future version of Android will remove the ability to use this method. Use the callbacks on InputMethodService as InputMethodService.onBindInput(), InputMethodService.onUnbindInput(), InputMethodService.onWindowShown(), InputMethodService.onWindowHidden(), etc.

Implement to return our standard InputMethodImpl.

onCreateInputMethodSessionInterface

Added in API level 3
public AbstractInputMethodService.AbstractInputMethodSessionImpl onCreateInputMethodSessionInterface ()

This method is deprecated.
Overriding or calling this method is strongly discouraged. Most methods in InputMethodSessionImpl have corresponding callbacks. Use InputMethodService.onFinishInput(), InputMethodService.onDisplayCompletions(CompletionInfo[]), InputMethodService.onUpdateExtractedText(int, ExtractedText), InputMethodService.onUpdateSelection(int, int, int, int, int, int) instead.

Implement to return our standard InputMethodSessionImpl.

IMEs targeting on Android U and above cannot override this method, or an LinkageError would be thrown.

onCreateInputView

Added in API level 3
public View onCreateInputView ()

Create and return the view hierarchy used for the input area (such as a soft keyboard). This will be called once, when the input area is first displayed. You can return null to have no input area; the default implementation returns null.

To control when the input view is displayed, implement onEvaluateInputViewShown(). To change the input view after the first one is created by this function, use setInputView(android.view.View).

Returns
View

onCustomImeSwitcherButtonRequestedVisible

public void onCustomImeSwitcherButtonRequestedVisible (boolean visible)

Called when the requested visibility of a custom IME Switcher button changes.

When the system provides an IME navigation bar, it may decide to show an IME Switcher button inside this bar. However, the IME can request hiding the bar provided by the system with getWindowInsetsController().hide(captionBar()) (the IME navigation bar provides captionBar insets to the IME window). If the request is successful, then it becomes the IME's responsibility to provide a custom IME Switcher button in its input view, with equivalent functionality.

This custom button is only requested to be visible when the system provides the IME navigation bar, both the bar and the IME Switcher button inside it should be visible, but the IME successfully requested to hide the bar. This does not depend on the current visibility of the IME. It could be called with true while the IME is hidden, in which case the IME should prepare to show the button as soon as the IME itself is shown.

This is only called when the requested visibility changes. The default value is false and as such, this will not be called initially if the resulting value is false.

This can be called at any time after onCreate(), even if the IME is not currently visible. However, this is not guaranteed to be called before the IME is shown, as it depends on when the IME requested hiding the IME navigation bar. If the request is sent during the showing flow (e.g. during onStartInputView(EditorInfo, boolean)), this will be called shortly after onWindowShown(), but before the first IME frame is drawn.

Parameters
visible boolean: whether the button is requested visible or not.

onDestroy

Added in API level 3
public void 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. If you override this method you must call through to the superclass implementation.

onDisplayCompletions

Added in API level 3
public void onDisplayCompletions (CompletionInfo[] completions)

Called when the application has reported auto-completion candidates that it would like to have the input method displayed. Typically these are only used when an input method is running in full-screen mode, since otherwise the user can see and interact with the pop-up window of completions shown by the application.

The default implementation here does nothing.

Parameters
completions CompletionInfo

onEvaluateFullscreenMode

Added in API level 3
public boolean onEvaluateFullscreenMode ()

Override this to control when the input method should run in fullscreen mode. The default implementation runs in fullsceen only when the screen is in landscape mode. If you change what this returns, you will need to call updateFullscreenMode() yourself whenever the returned value may have changed to have it re-evaluated and applied.

Returns
boolean

onEvaluateInputViewShown

Added in API level 3
public boolean onEvaluateInputViewShown ()

Override this to control when the soft input area should be shown to the user. The default implementation returns false when there is no hard keyboard or the keyboard is hidden unless the user shows an intention to use software keyboard. If you change what this returns, you will need to call updateInputViewShown() yourself whenever the returned value may have changed to have it re-evaluated and applied.

When you override this method, it is recommended to call super.onEvaluateInputViewShown() and return true when true is returned.


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

Returns
boolean

onExtractTextContextMenuItem

Added in API level 3
public boolean onExtractTextContextMenuItem (int id)

This is called when the user has selected a context menu item from the extracted text view, when running in fullscreen mode. The default implementation sends this action to the current InputConnection's InputConnection.performContextMenuAction(int), for it to be processed in underlying "real" editor. Re-implement this to provide whatever behavior you want.

Parameters
id int

Returns
boolean

onExtractedCursorMovement

Added in API level 3
public void onExtractedCursorMovement (int dx, 
                int dy)

This is called when the user has performed a cursor movement in the extracted text view, when it is running in fullscreen mode. The default implementation hides the candidates view when a vertical movement happens, but only if the extracted text editor has a vertical scroll bar because its text doesn't fit. Re-implement this to provide whatever behavior you want.

Parameters
dx int: The amount of cursor movement in the x dimension.

dy int: The amount of cursor movement in the y dimension.

onExtractedSelectionChanged

Added in API level 3
public void onExtractedSelectionChanged (int start, 
                int end)

This is called when the user has moved the cursor in the extracted text view, when running in fullsreen mode. The default implementation performs the corresponding selection change on the underlying text editor.

Parameters
start int

end int

onExtractedTextClicked

Added in API level 3
public void onExtractedTextClicked ()

This is called when the user has clicked on the extracted text view, when running in fullscreen mode. The default implementation hides the candidates view when this happens, but only if the extracted text editor has a vertical scroll bar because its text doesn't fit. Re-implement this to provide whatever behavior you want.

onExtractingInputChanged

Added in API level 3
public void onExtractingInputChanged (EditorInfo ei)

This is called when, while currently displayed in extract mode, the current input target changes. The default implementation will auto-hide the IME if the new target is not a full editor, since this can be a confusing experience for the user.

Parameters
ei EditorInfo

onFinishCandidatesView

Added in API level 3
public void onFinishCandidatesView (boolean finishingInput)

Called when the candidates view is being hidden from the user. This will be called either prior to hiding the window, or prior to switching to another target for editing.

The default implementation uses the InputConnection to clear any active composing text; you can override this (not calling the base class implementation) to perform whatever behavior you would like.

Parameters
finishingInput boolean: If true, onFinishInput() will be called immediately after.

onFinishInput

Added in API level 3
public void onFinishInput ()

Called to inform the input method that text input has finished in the last editor. At this point there may be a call to onStartInput(android.view.inputmethod.EditorInfo, boolean) to perform input in a new editor, or the input method may be left idle. This method is not called when input restarts in the same editor.

The default implementation uses the InputConnection to clear any active composing text; you can override this (not calling the base class implementation) to perform whatever behavior you would like.

onFinishInputView

Added in API level 3
public void onFinishInputView (boolean finishingInput)

Called when the input view is being hidden from the user. This will be called either prior to hiding the window, or prior to switching to another target for editing.

The default implementation uses the InputConnection to clear any active composing text; you can override this (not calling the base class implementation) to perform whatever behavior you would like.

Parameters
finishingInput boolean: If true, onFinishInput() will be called immediately after.

onFinishStylusHandwriting

Added in API level 33
public void onFinishStylusHandwriting ()

Called when the current stylus handwriting session was finished (either by the system or via finishStylusHandwriting(). When this is called, the ink window has been made invisible, and the IME no longer intercepts handwriting-related MotionEvents.

onGenericMotionEvent

Added in API level 17
public boolean onGenericMotionEvent (MotionEvent event)

Override this to intercept generic motion events before they are processed by the application. If you return true, the application will not itself process the event. If you return false, the normal application processing will occur as if the IME had not seen the event at all.

Parameters
event MotionEvent: The motion event being received.

Returns
boolean True if the event was handled in this function, false otherwise.

onInitializeInterface

Added in API level 3
public void onInitializeInterface ()

This is a hook that subclasses can use to perform initialization of their interface. It is called for you prior to any of your UI objects being created, both after the service is first created and after a configuration change happens.

onInlineSuggestionsResponse

Added in API level 30
public boolean onInlineSuggestionsResponse (InlineSuggestionsResponse response)

Called when Autofill responds back with InlineSuggestionsResponse containing inline suggestions.

Should be implemented by subclasses.

Parameters
response InlineSuggestionsResponse: InlineSuggestionsResponse passed back by Autofill. This value cannot be null.

Returns
boolean Whether the IME will use and render the inline suggestions.

onKeyDown

Added in API level 3
public boolean onKeyDown (int keyCode, 
                KeyEvent event)

Called back when a KeyEvent is forwarded from the target application.

The default implementation intercepts KeyEvent.KEYCODE_BACK if the IME is currently shown , to possibly hide it when the key goes up (if not canceled or long pressed). In addition, in fullscreen mode only, it will consume DPAD movement events to move the cursor in the extracted text view, not allowing them to perform navigation in the underlying application.

The default implementation does not take flags specified to setBackDisposition(int) into account, even on API version Build.VERSION_CODES.P and later devices. IME developers are responsible for making sure that their special handling for KeyEvent.KEYCODE_BACK are consistent with the flag they specified to setBackDisposition(int).

Parameters
keyCode int: The value in event.getKeyCode()

event KeyEvent: Description of the key event

Returns
boolean true if the event is consumed by the IME and the application no longer needs to consume it. Return false when the event should be handled as if the IME had not seen the event at all.

onKeyLongPress

Added in API level 5
public boolean onKeyLongPress (int keyCode, 
                KeyEvent event)

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

Parameters
keyCode int

event KeyEvent

Returns
boolean

onKeyMultiple

Added in API level 3
public boolean onKeyMultiple (int keyCode, 
                int count, 
                KeyEvent event)

Override this to intercept special key multiple events before they are processed by the application. If you return true, the application will not itself process the event. If you return false, the normal application processing will occur as if the IME had not seen the event at all.

The default implementation always returns false, except when in fullscreen mode, where it will consume DPAD movement events to move the cursor in the extracted text view, not allowing them to perform navigation in the underlying application.

Parameters
keyCode int

count int

event KeyEvent

Returns
boolean

onKeyUp

Added in API level 3
public boolean onKeyUp (int keyCode, 
                KeyEvent event)

Override this to intercept key up events before they are processed by the application. If you return true, the application will not itself process the event. If you return false, the normal application processing will occur as if the IME had not seen the event at all.

The default implementation intercepts KeyEvent.KEYCODE_BACK to hide the current IME UI if it is shown. In addition, in fullscreen mode only, it will consume DPAD movement events to move the cursor in the extracted text view, not allowing them to perform navigation in the underlying application.

Parameters
keyCode int

event KeyEvent

Returns
boolean

onPrepareStylusHandwriting

Added in API level 33
public void onPrepareStylusHandwriting ()

Called to prepare stylus handwriting. The system calls this before the onStartStylusHandwriting() request.

Note: The system tries to call this as early as possible, when it detects that handwriting stylus input is imminent. However, that a subsequent call to onStartStylusHandwriting() actually happens is not guaranteed.

onShouldVerifyKeyEvent

public boolean onShouldVerifyKeyEvent (KeyEvent keyEvent)

Received by the IME before dispatch to onKeyDown(int, android.view.KeyEvent) to let the system know if the KeyEvent needs to be verified that it originated from the system. KeyEvents may originate from outside of the system and any sensitive keys should be marked for verification. One example of this could be using key shortcuts for switching to another IME.

Parameters
keyEvent KeyEvent: the event that may need verification. This value cannot be null.

Returns
boolean true if KeyEvent should have its HMAC verified before dispatch, false otherwise.

onShowInputRequested

Added in API level 3
public boolean onShowInputRequested (int flags, 
                boolean configChange)

The system has decided that it may be time to show your input method. This is called due to a corresponding call to your InputMethod.showSoftInput() method. The default implementation uses onEvaluateInputViewShown(), onEvaluateFullscreenMode(), and the current configuration to decide whether the input view should be shown at this point.

Parameters
flags int: Value is either 0 or a combination of InputMethod.SHOW_EXPLICIT, and InputMethod.SHOW_FORCED

configChange boolean: This is true if we are re-showing due to a configuration change.

Returns
boolean Returns true to indicate that the window should be shown.

onStartCandidatesView

Added in API level 3
public void onStartCandidatesView (EditorInfo editorInfo, 
                boolean restarting)

Called when only the candidates view has been shown for showing processing as the user enters text through a hard keyboard. This will always be called after onStartInput(EditorInfo, boolean), allowing you to do your general setup there and just view-specific setup here. You are guaranteed that onCreateCandidatesView() will have been called some time before this function is called.

Note that this will not be called when the input method is running in full editing mode, and thus receiving onStartInputView(EditorInfo, boolean) to initiate that operation. This is only for the case when candidates are being shown while the input method editor is hidden but wants to show its candidates UI as text is entered through some other mechanism.

Parameters
editorInfo EditorInfo: Description of the type of text being edited.

restarting boolean: Set to true if we are restarting input on the same text field as before.

onStartConnectionlessStylusHandwriting

Added in API level 35
public boolean onStartConnectionlessStylusHandwriting (int inputType, 
                CursorAnchorInfo cursorAnchorInfo)

Called when an app requests to start a connectionless stylus handwriting session using one of InputMethodManager.startConnectionlessStylusHandwriting(View, CursorAnchorInfo, Executor, ConnectionlessHandwritingCallback), InputMethodManager.startConnectionlessStylusHandwritingForDelegation(android.view.View, android.view.inputmethod.CursorAnchorInfo, java.util.concurrent.Executor, android.view.inputmethod.ConnectionlessHandwritingCallback), or InputMethodManager.startConnectionlessStylusHandwritingForDelegation(android.view.View, android.view.inputmethod.CursorAnchorInfo, java.lang.String, java.util.concurrent.Executor, android.view.inputmethod.ConnectionlessHandwritingCallback).

A connectionless stylus handwriting session differs from a regular session in that an input connection is not used to communicate with a text editor. Instead, the recognised text is delivered when the IME finishes the connectionless session using finishConnectionlessStylusHandwriting(java.lang.CharSequence).

If the IME can start the connectionless handwriting session, it should return true, ensure its inking views are attached to the getStylusHandwritingWindow(), and handle stylus input received from onStylusHandwritingMotionEvent(android.view.MotionEvent) on the getStylusHandwritingWindow().

Parameters
inputType int

cursorAnchorInfo CursorAnchorInfo: This value may be null.

Returns
boolean

onStartInput

Added in API level 3
public void onStartInput (EditorInfo attribute, 
                boolean restarting)

Called to inform the input method that text input has started in an editor. You should use this callback to initialize the state of your input to match the state of the editor given to it.

Parameters
attribute EditorInfo: The attributes of the editor that input is starting in.

restarting boolean: Set to true if input is restarting in the same editor such as because the application has changed the text in the editor. Otherwise will be false, indicating this is a new session with the editor.

onStartInputView

Added in API level 3
public void onStartInputView (EditorInfo editorInfo, 
                boolean restarting)

Called when the input view is being shown and input has started on a new editor. This will always be called after onStartInput(EditorInfo, boolean), allowing you to do your general setup there and just view-specific setup here. You are guaranteed that onCreateInputView() will have been called some time before this function is called.

Parameters
editorInfo EditorInfo: Description of the type of text being edited.

restarting boolean: Set to true if we are restarting input on the same text field as before.

onStartStylusHandwriting

Added in API level 33
public boolean onStartStylusHandwriting ()

Called when an app requests stylus handwriting InputMethodManager.startStylusHandwriting(View). This will always be preceded by onStartInput(android.view.inputmethod.EditorInfo, boolean) for the EditorInfo and InputConnection for which stylus handwriting is being requested. If the IME supports handwriting for the current input, it should return true, ensure its inking views are attached to the getStylusHandwritingWindow(), and handle stylus input received from onStylusHandwritingMotionEvent(android.view.MotionEvent) on the getStylusHandwritingWindow() via getCurrentInputConnection().

Returns
boolean true if IME can honor the request, false if IME cannot at this time.

onStylusHandwritingMotionEvent

Added in API level 33
public void onStylusHandwritingMotionEvent (MotionEvent motionEvent)

Called after onStartStylusHandwriting() returns true for every Stylus MotionEvent. By default, this method forwards all MotionEvents to the getStylusHandwritingWindow() once its visible, however IME can override it to receive them sooner.

Parameters
motionEvent MotionEvent: MotionEvent from stylus. This value cannot be null.

onTrackballEvent

Added in API level 3
public boolean onTrackballEvent (MotionEvent event)

Override this to intercept trackball motion events before they are processed by the application. If you return true, the application will not itself process the event. If you return false, the normal application processing will occur as if the IME had not seen the event at all.

Parameters
event MotionEvent: The motion event being received.

Returns
boolean True if the event was handled in this function, false otherwise.

onUnbindInput

Added in API level 3
public void onUnbindInput ()

Called when the previous bound client is no longer associated with the input method. After returning getCurrentInputBinding() and getCurrentInputConnection() will no longer return valid objects.

onUpdateCursor

Added in API level 3
Deprecated in API level 21
public void onUpdateCursor (Rect newCursor)

This method was deprecated in API level 21.
Use onUpdateCursorAnchorInfo(android.view.inputmethod.CursorAnchorInfo) instead.

Called when the application has reported a new location of its text cursor. This is only called if explicitly requested by the input method. The default implementation does nothing.

Parameters
newCursor Rect

onUpdateCursorAnchorInfo

Added in API level 21
public void onUpdateCursorAnchorInfo (CursorAnchorInfo cursorAnchorInfo)

Called when the application has reported a new location of its text insertion point and characters in the composition string. This is only called if explicitly requested by the input method. The default implementation does nothing.

Parameters
cursorAnchorInfo CursorAnchorInfo: The positional information of the text insertion point and the composition string.

onUpdateEditorToolType

Added in API level 34
public void onUpdateEditorToolType (int toolType)

Called when the user tapped or clicked an editor. This can be useful when IME makes a decision of showing Virtual keyboard based on what MotionEvent.getToolType(int) was used to click the editor. e.g. when toolType is MotionEvent.TOOL_TYPE_STYLUS, IME may choose to show a companion widget instead of normal virtual keyboard.

This method is called after onStartInput(android.view.inputmethod.EditorInfo, boolean) and before onStartInputView(android.view.inputmethod.EditorInfo, boolean) when editor was clicked with a known tool type.

Default implementation does nothing.

Parameters
toolType int: what MotionEvent.getToolType(int) was used to click on editor. Value is MotionEvent.TOOL_TYPE_UNKNOWN, MotionEvent.TOOL_TYPE_FINGER, MotionEvent.TOOL_TYPE_STYLUS, MotionEvent.TOOL_TYPE_MOUSE, MotionEvent.TOOL_TYPE_ERASER, or android.view.MotionEvent.TOOL_TYPE_PALM

onUpdateExtractedText

Added in API level 3
public void onUpdateExtractedText (int token, 
                ExtractedText text)

Called when the application has reported new extracted text to be shown due to changes in its current text state. The default implementation here places the new text in the extract edit text, when the input method is running in fullscreen mode.

Parameters
token int

text ExtractedText

onUpdateExtractingViews

Added in API level 3
public void onUpdateExtractingViews (EditorInfo ei)

Called when the fullscreen-mode extracting editor info has changed, to update the state of its UI such as the action buttons shown. You do not need to deal with this if you are using the standard full screen extract UI. If replacing it, you will need to re-implement this to put the appropriate action button in your own UI and handle it, and perform any other changes.

The standard implementation turns on or off its accessory area depending on whether there is an action button, and hides or shows the entire extract area depending on whether it makes sense for the current editor. In particular, a InputType.TYPE_NULL or InputType.TYPE_TEXT_VARIATION_FILTER input type will turn off the extract area since there is no text to be shown.

Parameters
ei EditorInfo

onUpdateExtractingVisibility

Added in API level 3
public void onUpdateExtractingVisibility (EditorInfo ei)

Called when the fullscreen-mode extracting editor info has changed, to determine whether the extracting (extract text and candidates) portion of the UI should be shown. The standard implementation hides or shows the extract area depending on whether it makes sense for the current editor. In particular, a InputType.TYPE_NULL input type or EditorInfo.IME_FLAG_NO_EXTRACT_UI flag will turn off the extract area since there is no text to be shown.

Parameters
ei EditorInfo

onUpdateSelection

Added in API level 3
public void onUpdateSelection (int oldSelStart, 
                int oldSelEnd, 
                int newSelStart, 
                int newSelEnd, 
                int candidatesStart, 
                int candidatesEnd)

Called when the application has reported a new selection region of the text. This is called whether or not the input method has requested extracted text updates, although if so it will not receive this call if the extracted text has changed as well.

The default implementation takes care of updating the cursor in the extract text, if it is being shown.

Parameters
oldSelStart int

oldSelEnd int

newSelStart int

newSelEnd int

candidatesStart int

candidatesEnd int

onViewClicked

Added in API level 14
Deprecated in API level 29
public void onViewClicked (boolean focusChanged)

This method was deprecated in API level 29.
The method may not be called for composite View that works as a giant "Canvas", which can host its own UI hierarchy and sub focus state. WebView is a good example. Application / IME developers should not rely on this method. If your goal is just being notified when an on-going input is interrupted, simply monitor onFinishInput(). If your goal is to know what MotionEvent.getToolType(int) clicked on editor, use onUpdateEditorToolType(int) instead.

Called when the user tapped or clicked a text view. IMEs can't rely on this method being called because this was not part of the original IME protocol, so applications with custom text editing written before this method appeared will not call to inform the IME of this interaction.

Parameters
focusChanged boolean: true if the user changed the focused view by this click.

onWindowHidden

Added in API level 3
public void onWindowHidden ()

Called when the input method window has been hidden from the user, after previously being visible.

onWindowShown

Added in API level 3
public void onWindowShown ()

Called immediately before the input method window is shown to the user. You could override this to prepare for the window to be shown (update view structure etc).

requestHideSelf

Added in API level 3
public void requestHideSelf (int flags)

Close this input method's soft input area, removing it from the display. The input method will continue running, but the user can no longer use it to generate input by touching the screen.

Parameters
flags int: Value is either 0 or a combination of InputMethodManager.HIDE_IMPLICIT_ONLY, and InputMethodManager.HIDE_NOT_ALWAYS

requestShowSelf

Added in API level 28
public final void requestShowSelf (int flags)

Show the input method's soft input area, so the user sees the input method window and can interact with it.

Parameters
flags int: Value is either 0 or a combination of InputMethodManager.SHOW_IMPLICIT, and InputMethodManager.SHOW_FORCED

sendDefaultEditorAction

Added in API level 3
public boolean sendDefaultEditorAction (boolean fromEnterKey)

Ask the input target to execute its default action via InputConnection.performEditorAction().

For compatibility, this method does not execute a custom action even if EditorInfo.actionLabel is set. The implementor should directly call InputConnection.performEditorAction() with EditorInfo.actionId if they want to execute a custom action.

Parameters
fromEnterKey boolean: If true, this will be executed as if the user had pressed an enter key on the keyboard, that is it will not be done if the editor has set EditorInfo.IME_FLAG_NO_ENTER_ACTION. If false, the action will be sent regardless of how the editor has set that flag.

Returns
boolean Returns a boolean indicating whether an action has been sent. If false, either the editor did not specify a default action or it does not want an action from the enter key. If true, the action was sent (or there was no input connection at all).

sendDownUpKeyEvents

Added in API level 3
public void sendDownUpKeyEvents (int keyEventCode)

Send the given key event code (as defined by KeyEvent) to the current input connection is a key down + key up event pair. The sent events have KeyEvent.FLAG_SOFT_KEYBOARD set, so that the recipient can identify them as coming from a software input method, and KeyEvent.FLAG_KEEP_TOUCH_MODE, so that they don't impact the current touch mode of the UI.

Note that it's discouraged to send such key events in normal operation; this is mainly for use with InputType.TYPE_NULL type text fields, or for non-rich input methods. A reasonably capable software input method should use the InputConnection.commitText(CharSequence, int) family of methods to send text to an application, rather than sending key events.

Parameters
keyEventCode int: The raw key code to send, as defined by KeyEvent.

sendKeyChar

Added in API level 3
public void sendKeyChar (char charCode)

Send the given UTF-16 character to the current input connection. Most characters will be delivered simply by calling InputConnection.commitText() with the character; some, however, may be handled different. In particular, the enter character ('\n') will either be delivered as an action code or a raw key event, as appropriate. Consider this as a convenience method for IMEs that do not have a full implementation of actions; a fully complying IME will decide of the right action for each event and will likely never call this method except maybe to handle events coming from an actual hardware keyboard.

Parameters
charCode char: The UTF-16 character code to send.

setBackDisposition

Added in API level 11
public void setBackDisposition (int disposition)

Sets the disposition mode that indicates the expected affordance for the back button.

Keep in mind that specifying this flag does not change the the default behavior of onKeyDown(int, android.view.KeyEvent). It is IME developers' responsibility for making sure that their custom implementation of onKeyDown(int, android.view.KeyEvent) is consistent with the mode specified to this API.

setCandidatesView

Added in API level 3
public void setCandidatesView (View view)

Replaces the current candidates view with a new one. You only need to call this when dynamically changing the view; normally, you should implement onCreateCandidatesView() and create your view when first needed by the input method.

Parameters
view View

setCandidatesViewShown

Added in API level 3
public void setCandidatesViewShown (boolean shown)

Controls the visibility of the candidates display area. By default it is hidden.

Parameters
shown boolean

setExtractView

Added in API level 3
public void setExtractView (View view)

Parameters
view View

setExtractViewShown

Added in API level 3
public void setExtractViewShown (boolean shown)

Controls the visibility of the extracted text area. This only applies when the input method is in fullscreen mode, and thus showing extracted text. When false, the extracted text will not be shown, allowing some of the application to be seen behind. This is normally set for you by onUpdateExtractingVisibility(EditorInfo). This controls the visibility of both the extracted text and candidate view; the latter since it is not useful if there is no text to see.

Parameters
shown boolean

setInputView

Added in API level 3
public void setInputView (View view)

Replaces the current input view with a new one. You only need to call this when dynamically changing the view; normally, you should implement onCreateInputView() and create your view when first needed by the input method.

Parameters
view View

setStylusHandwritingRegion

public final void setStylusHandwritingRegion (Region handwritingRegion)

Sets a new stylus handwriting region as user continues to write on an editor on screen. Stylus strokes that are started within the touchableRegion are treated as continuation of handwriting and all the events outside are passed-through to the IME target app, causing stylus handwriting to finish finishStylusHandwriting(). By default, WindowManager.getMaximumWindowMetrics() is handwritable and touchableRegion resets after each handwriting session.

For example, the IME can use this API to dynamically expand the stylus handwriting region on every stylus stroke as user continues to write on an editor. The region should grow around the last stroke so that a UI element below the IME window is still interactable when it is spaced sufficiently away (~2 character dimensions) from last stroke.

Note: Setting handwriting touchable region is supported on IMEs that support stylus handwriting InputMethodInfo.supportsStylusHandwriting().

Parameters
handwritingRegion Region: new stylus handwritable Region that can accept stylus touch. This value cannot be null.

setStylusHandwritingSessionTimeout

Added in API level 34
public final void setStylusHandwritingSessionTimeout (Duration duration)

Sets the duration after which an ongoing stylus handwriting session that hasn't received new MotionEvents will time out and finishStylusHandwriting() will be called. The maximum allowed duration is returned by getStylusHandwritingIdleTimeoutMax(), larger values will be clamped. Note: this value is bound to the InputMethodService instance and resets to the default whenever a new instance is constructed.

Parameters
duration Duration: timeout to set. This value cannot be null.

setTheme

Added in API level 3
public void setTheme (int theme)

You can call this to customize the theme used by your IME's window. This theme should typically be one that derives from R.style.Theme_InputMethod, which is the default theme you will get. This must be set before onCreate(), so you will typically call it in your constructor with the resource ID of your custom theme.

Parameters
theme int: The style resource describing the theme.

shouldOfferSwitchingToNextInputMethod

Added in API level 28
public final boolean shouldOfferSwitchingToNextInputMethod ()

Returns true if the current IME needs to offer the users ways to switch to a next input method (e.g. a globe key.). When an IME sets supportsSwitchingToNextInputMethod and this method returns true, the IME has to offer ways to to invoke switchToNextInputMethod(boolean) accordingly.

Note that the system determines the most appropriate next input method and subtype in order to provide the consistent user experience in switching between IMEs and subtypes.

Returns
boolean

showStatusIcon

Added in API level 3
public void showStatusIcon (int iconResId)

Parameters
iconResId int

showWindow

Added in API level 3
public void showWindow (boolean showInput)

Parameters
showInput boolean

switchInputMethod

Added in API level 3
public void switchInputMethod (String id)

Force switch to a new input method, as identified by id. This input method will be destroyed, and the requested one started on the current input field.

Parameters
id String: Unique identifier of the new input method to start.

Throws
IllegalArgumentException if the input method is unknown or filtered by the rules of package visibility.

switchInputMethod

Added in API level 28
public final void switchInputMethod (String id, 
                InputMethodSubtype subtype)

Force switch to a new input method, as identified by id. This input method will be destroyed, and the requested one started on the current input field.

Parameters
id String: Unique identifier of the new input method to start.

subtype InputMethodSubtype: The new subtype of the new input method to be switched to.

Throws
IllegalArgumentException if the input method is unknown or filtered by the rules of package visibility.

switchToNextInputMethod

Added in API level 28
public final boolean switchToNextInputMethod (boolean onlyCurrentIme)

Force switch to the next input method and subtype. If there is no IME enabled except current IME and subtype, do nothing.

Parameters
onlyCurrentIme boolean: if true, the framework will find the next subtype which belongs to the current IME

Returns
boolean true if the current input method and subtype was successfully switched to the next input method and subtype.

switchToPreviousInputMethod

Added in API level 28
public final boolean switchToPreviousInputMethod ()

Force switch to the last used input method and subtype. If the last input method didn't have any subtypes, the framework will simply switch to the last input method with no subtype specified.

Returns
boolean true if the current input method and subtype was successfully switched to the last used input method and subtype.

updateFullscreenMode

Added in API level 3
public void updateFullscreenMode ()

Re-evaluate whether the input method should be running in fullscreen mode, and update its UI if this has changed since the last time it was evaluated. This will call onEvaluateFullscreenMode() to determine whether it should currently run in fullscreen mode. You can use isFullscreenMode() to determine if the input method is currently running in fullscreen mode.

updateInputViewShown

Added in API level 3
public void updateInputViewShown ()

Re-evaluate whether the soft input area should currently be shown, and update its UI if this has changed since the last time it was evaluated. This will call onEvaluateInputViewShown() to determine whether the input view should currently be shown. You can use isInputViewShown() to determine if the input view is currently shown.

Protected methods

dump

Added in API level 3
protected void dump (FileDescriptor fd, 
                PrintWriter fout, 
                String[] args)

Performs a dump of the InputMethodService's internal state. Override to add your own information to the dump.

Parameters
fd FileDescriptor: The raw file descriptor that the dump is being sent to.

fout PrintWriter: The PrintWriter to which you should dump your state. This will be closed for you after you return.

args String: additional arguments to the dump request.

onCurrentInputMethodSubtypeChanged

Added in API level 11
protected void onCurrentInputMethodSubtypeChanged (InputMethodSubtype newSubtype)

Called when the subtype was changed.

Parameters
newSubtype InputMethodSubtype: the subtype which is being changed to.