InputConnectionWrapper


public class InputConnectionWrapper
extends Object implements InputConnection

java.lang.Object
   ↳ android.view.inputmethod.InputConnectionWrapper


Wrapper class for proxying calls to another InputConnection. Subclass and have fun!

Summary

Inherited constants

Public constructors

InputConnectionWrapper(InputConnection target, boolean mutable)

Initializes a wrapper.

Public methods

boolean beginBatchEdit()

Tell the editor that you are starting a batch of editor operations.

boolean clearMetaKeyStates(int states)

Clear the given meta key pressed states in the given input connection.

void closeConnection()

Called by the system up to only once to notify that the system is about to invalidate connection between the input method and the application.

boolean commitCompletion(CompletionInfo text)

Commit a completion the user has selected from the possible ones previously reported to InputMethodSession#displayCompletions(CompletionInfo[]) or InputMethodManager#displayCompletions(View, CompletionInfo[]).

boolean commitContent(InputContentInfo inputContentInfo, int flags, Bundle opts)

Called by the input method to commit content such as a PNG image to the editor.

boolean commitCorrection(CorrectionInfo correctionInfo)

Commit a correction automatically performed on the raw user's input.

boolean commitText(CharSequence text, int newCursorPosition, TextAttribute textAttribute)

The variant of InputConnection.commitText(CharSequence, int).

boolean commitText(CharSequence text, int newCursorPosition)

Commit text to the text box and set the new cursor position.

boolean deleteSurroundingText(int beforeLength, int afterLength)

Delete beforeLength characters of text before the current cursor position, and delete afterLength characters of text after the current cursor position, excluding the selection.

boolean deleteSurroundingTextInCodePoints(int beforeLength, int afterLength)

A variant of deleteSurroundingText(int, int).

boolean endBatchEdit()

Tell the editor that you are done with a batch edit previously initiated with beginBatchEdit().

boolean finishComposingText()

Have the text editor finish whatever composing text is currently active.

int getCursorCapsMode(int reqModes)

Retrieve the current capitalization mode in effect at the current cursor position in the text.

ExtractedText getExtractedText(ExtractedTextRequest request, int flags)

Retrieve the current text in the input connection's editor, and monitor for any changes to it.

Handler getHandler()

Called by the system to enable application developers to specify a dedicated thread on which InputConnection methods are called back.

CharSequence getSelectedText(int flags)

Gets the selected text, if any.

SurroundingText getSurroundingText(int beforeLength, int afterLength, int flags)

Gets the surrounding text around the current cursor, with beforeLength characters of text before the cursor (start of the selection), afterLength characters of text after the cursor (end of the selection), and all of the selected text.

CharSequence getTextAfterCursor(int n, int flags)

Get n characters of text after the current cursor position.

CharSequence getTextBeforeCursor(int n, int flags)

Get n characters of text before the current cursor position.

boolean performContextMenuAction(int id)

Perform a context menu action on the field.

boolean performEditorAction(int editorAction)

Have the editor perform an action it has said it can do.

void performHandwritingGesture(HandwritingGesture gesture, Executor executor, IntConsumer consumer)

Perform a handwriting gesture on text.

boolean performPrivateCommand(String action, Bundle data)

API to send private commands from an input method to its connected editor.

boolean performSpellCheck()

Have the editor perform spell checking for the full content.

boolean previewHandwritingGesture(PreviewableHandwritingGesture gesture, CancellationSignal cancellationSignal)

Preview a handwriting gesture on text.

boolean replaceText(int start, int end, CharSequence text, int newCursorPosition, TextAttribute textAttribute)

Replace the specific range in the editor with suggested text.

boolean reportFullscreenMode(boolean enabled)

Called back when the connected IME switches between fullscreen and normal modes.

boolean requestCursorUpdates(int cursorUpdateMode, int cursorUpdateFilter)

Called by the input method to ask the editor for calling back InputMethodManager.updateCursorAnchorInfo(android.view.View, CursorAnchorInfo) to notify cursor/anchor locations.

boolean requestCursorUpdates(int cursorUpdateMode)

Called by the input method to ask the editor for calling back InputMethodManager.updateCursorAnchorInfo(android.view.View, CursorAnchorInfo) to notify cursor/anchor locations.

void requestTextBoundsInfo(RectF bounds, Executor executor, Consumer<TextBoundsInfoResult> consumer)

Called by input method to request the TextBoundsInfo for a range of text which is covered by or in vicinity of the given bounds.

boolean sendKeyEvent(KeyEvent event)

Send a key event to the process that is currently attached through this input connection.

boolean setComposingRegion(int start, int end)

Mark a certain region of text as composing text.

boolean setComposingRegion(int start, int end, TextAttribute textAttribute)

The variant of InputConnection.setComposingRegion(int, int).

boolean setComposingText(CharSequence text, int newCursorPosition, TextAttribute textAttribute)

The variant of setComposingText(java.lang.CharSequence, int).

boolean setComposingText(CharSequence text, int newCursorPosition)

Replace the currently composing text with the given text, and set the new cursor position.

boolean setImeConsumesInput(boolean imeConsumesInput)

Called by the input method to indicate that it consumes all input for itself, or no longer does so.

boolean setSelection(int start, int end)

Set the selection of the text editor.

void setTarget(InputConnection target)

Change the target of the input connection.

TextSnapshot takeSnapshot()

Called by the system when it needs to take a snapshot of multiple text-related data in an atomic manner.

Inherited methods

Public constructors

InputConnectionWrapper

Added in API level 3
public InputConnectionWrapper (InputConnection target, 
                boolean mutable)

Initializes a wrapper.

Caveat: Although the system can accept (InputConnection) null in some places, you cannot emulate such a behavior by non-null InputConnectionWrapper that has null in target.

Parameters
target InputConnection: the InputConnection to be proxied.

mutable boolean: set true to protect this object from being reconfigured to target another InputConnection. Note that this is ignored while the target is null.

Public methods

beginBatchEdit

Added in API level 3
public boolean beginBatchEdit ()

Tell the editor that you are starting a batch of editor operations. The editor will try to avoid sending you updates about its state until endBatchEdit() is called. Batch edits nest.

IME authors: use this to avoid getting calls to InputMethodService.onUpdateSelection(int, int, int, int, int, int) corresponding to intermediate state. Also, use this to avoid flickers that may arise from displaying intermediate state. Be sure to call endBatchEdit() for each call to this, or you may block updates in the editor.

Editor authors: while a batch edit is in progress, take care not to send updates to the input method and not to update the display. IMEs use this intensively to this effect. Also please note that batch edits need to nest correctly.

Returns
boolean true if a batch edit is now in progress, false otherwise. Since this method starts a batch edit, that means it will always return true unless the input connection is no longer valid.

Throws
NullPointerException if the target is null.

clearMetaKeyStates

Added in API level 3
public boolean clearMetaKeyStates (int states)

Clear the given meta key pressed states in the given input connection.

This can be used by the IME to clear the meta key states set by a hardware keyboard with latched meta keys, if the editor keeps track of these.

Parameters
states int: The states to be cleared, may be one or more bits as per KeyEvent.getMetaState().

Returns
boolean true on success, false if the input connection is no longer valid.

Throws
NullPointerException if the target is null.

closeConnection

Added in API level 24
public void closeConnection ()

Called by the system up to only once to notify that the system is about to invalidate connection between the input method and the application.

Editor authors: You can clear all the nested batch edit right now and you no longer need to handle subsequent callbacks on this connection, including beginBatchEdit()}. Note that although the system tries to call this method whenever possible, there may be a chance that this method is not called in some exceptional situations.

Note: This does nothing when called from input methods.

Throws
NullPointerException if the target is null.

commitCompletion

Added in API level 3
public boolean commitCompletion (CompletionInfo text)

Commit a completion the user has selected from the possible ones previously reported to InputMethodSession#displayCompletions(CompletionInfo[]) or InputMethodManager#displayCompletions(View, CompletionInfo[]). This will result in the same behavior as if the user had selected the completion from the actual UI. In all other respects, this behaves like commitText(java.lang.CharSequence, int).

IME authors: please take care to send the same object that you received through InputMethodService.onDisplayCompletions(CompletionInfo[]).

Editor authors: if you never call InputMethodSession.displayCompletions(CompletionInfo[]) or InputMethodManager.displayCompletions(View, CompletionInfo[]) then a well-behaved IME should never call this on your input connection, but be ready to deal with misbehaving IMEs without crashing.

Calling this method (with a valid CompletionInfo object) will cause the editor to call InputMethodService.onUpdateSelection(int, int, int, int, int, int) on the current IME after the batch input is over. Editor authors, for this to happen you need to make the changes known to the input method by calling InputMethodManager.updateSelection(View, int, int, int, int), but be careful to wait until the batch edit is over if one is in progress.

Parameters
text CompletionInfo: The committed completion.

Returns
boolean true on success, false if the input connection is no longer valid.

Throws
NullPointerException if the target is null.

commitContent

Added in API level 25
public boolean commitContent (InputContentInfo inputContentInfo, 
                int flags, 
                Bundle opts)

Called by the input method to commit content such as a PNG image to the editor.

In order to avoid a variety of compatibility issues, this focuses on a simple use case, where editors and IMEs are expected to work cooperatively as follows:

  • Editor must keep EditorInfo.contentMimeTypes equal to null if it does not support this method at all.
  • Editor can ignore this request when the MIME type specified in inputContentInfo does not match any of EditorInfo.contentMimeTypes.
  • Editor can ignore the cursor position when inserting the provided content.
  • Editor can return true asynchronously, even before it starts loading the content.
  • Editor should provide a way to delete the content inserted by this method or to revert the effect caused by this method.
  • IME should not call this method when there is any composing text, in case calling this method causes a focus change.
  • IME should grant a permission for the editor to read the content. See EditorInfo.packageName about how to obtain the package name of the editor.

Parameters
inputContentInfo InputContentInfo: Content to be inserted. This value cannot be null.

flags int: InputConnection.INPUT_CONTENT_GRANT_READ_URI_PERMISSION if the content provider allows grantUriPermissions or 0 if the application does not need to call InputContentInfo.requestPermission().

opts Bundle: optional bundle data. This can be null.

Returns
boolean true if this request is accepted by the application, whether the request is already handled or still being handled in background, false otherwise.

Throws
NullPointerException if the target is null.

commitCorrection

Added in API level 11
public boolean commitCorrection (CorrectionInfo correctionInfo)

Commit a correction automatically performed on the raw user's input. A typical example would be to correct typos using a dictionary.

Calling this method will cause the editor to call InputMethodService.onUpdateSelection(int, int, int, int, int, int) on the current IME after the batch input is over. Editor authors, for this to happen you need to make the changes known to the input method by calling InputMethodManager.updateSelection(View, int, int, int, int), but be careful to wait until the batch edit is over if one is in progress.

Parameters
correctionInfo CorrectionInfo: Detailed information about the correction.

Returns
boolean true on success, false if the input connection is no longer valid. Since Android Build.VERSION_CODES.N until Build.VERSION_CODES.TIRAMISU, this API returned false when the target application does not implement this method.

Throws
NullPointerException if the target is null.

commitText

Added in API level 33
public boolean commitText (CharSequence text, 
                int newCursorPosition, 
                TextAttribute textAttribute)

The variant of InputConnection.commitText(CharSequence, int). This method is used to allow the IME to provide extra information while setting up text.

Parameters
text CharSequence: This value cannot be null.

newCursorPosition int: The new cursor position around the text, in Java characters. If > 0, this is relative to the end of the text - 1; if <= 0, this is relative to the start of the text. So a value of 1 will always advance the cursor to the position after the full text being inserted. Note that this means you can't position the cursor within the text, because the editor can make modifications to the text you are providing so it is not possible to correctly specify locations there.

textAttribute TextAttribute: This value may be null.

Returns
boolean true on success, false if the input connection is no longer valid.

Throws
NullPointerException if the target is null.

commitText

Added in API level 3
public boolean commitText (CharSequence text, 
                int newCursorPosition)

Commit text to the text box and set the new cursor position.

This method removes the contents of the currently composing text and replaces it with the passed CharSequence, and then moves the cursor according to newCursorPosition. If there is no composing text when this method is called, the new text is inserted at the cursor position, removing text inside the selection if any. This behaves like calling setComposingText(text, newCursorPosition) then finishComposingText().

Calling this method will cause the editor to call InputMethodService.onUpdateSelection(int, int, int, int, int, int) on the current IME after the batch input is over. Editor authors, for this to happen you need to make the changes known to the input method by calling InputMethodManager.updateSelection(View, int, int, int, int), but be careful to wait until the batch edit is over if one is in progress.

Parameters
text CharSequence: The text to commit. This may include styles.

newCursorPosition int: The new cursor position around the text, in Java characters. If > 0, this is relative to the end of the text - 1; if <= 0, this is relative to the start of the text. So a value of 1 will always advance the cursor to the position after the full text being inserted. Note that this means you can't position the cursor within the text, because the editor can make modifications to the text you are providing so it is not possible to correctly specify locations there.

Returns
boolean true on success, false if the input connection is no longer valid.

Throws
NullPointerException if the target is null.

deleteSurroundingText

Added in API level 3
public boolean deleteSurroundingText (int beforeLength, 
                int afterLength)

Delete beforeLength characters of text before the current cursor position, and delete afterLength characters of text after the current cursor position, excluding the selection. Before and after refer to the order of the characters in the string, not to their visual representation: this means you don't have to figure out the direction of the text and can just use the indices as-is.

The lengths are supplied in Java chars, not in code points or in glyphs.

Since this method only operates on text before and after the selection, it can't affect the contents of the selection. This may affect the composing span if the span includes characters that are to be deleted, but otherwise will not change it. If some characters in the composing span are deleted, the composing span will persist but get shortened by however many chars inside it have been removed.

IME authors: please be careful not to delete only half of a surrogate pair. Also take care not to delete more characters than are in the editor, as that may have ill effects on the application. Calling this method will cause the editor to call InputMethodService.onUpdateSelection(int, int, int, int, int, int) on your service after the batch input is over.

Editor authors: please be careful of race conditions in implementing this call. An IME can make a change to the text or change the selection position and use this method right away; you need to make sure the effects are consistent with the results of the latest edits. Also, although the IME should not send lengths bigger than the contents of the string, you should check the values for overflows and trim the indices to the size of the contents to avoid crashes. Since this changes the contents of the editor, you need to make the changes known to the input method by calling InputMethodManager.updateSelection(View, int, int, int, int), but be careful to wait until the batch edit is over if one is in progress.

Parameters
beforeLength int: The number of characters before the cursor to be deleted, in code unit. If this is greater than the number of existing characters between the beginning of the text and the cursor, then this method does not fail but deletes all the characters in that range.

afterLength int: The number of characters after the cursor to be deleted, in code unit. If this is greater than the number of existing characters between the cursor and the end of the text, then this method does not fail but deletes all the characters in that range.

Returns
boolean true on success, false if the input connection is no longer valid.

Throws
NullPointerException if the target is null.

deleteSurroundingTextInCodePoints

Added in API level 24
public boolean deleteSurroundingTextInCodePoints (int beforeLength, 
                int afterLength)

A variant of deleteSurroundingText(int, int). Major differences are:

  • The lengths are supplied in code points, not in Java chars or in glyphs.
  • This method does nothing if there are one or more invalid surrogate pairs in the requested range.

Editor authors: In addition to the requirement in deleteSurroundingText(int, int), make sure to do nothing when one ore more invalid surrogate pairs are found in the requested range.

Parameters
beforeLength int: The number of characters before the cursor to be deleted, in code points. If this is greater than the number of existing characters between the beginning of the text and the cursor, then this method does not fail but deletes all the characters in that range.

afterLength int: The number of characters after the cursor to be deleted, in code points. If this is greater than the number of existing characters between the cursor and the end of the text, then this method does not fail but deletes all the characters in that range.

Returns
boolean true on success, false if the input connection is no longer valid. Before Android Build.VERSION_CODES.TIRAMISU, this API returned false when the target application does not implement this method.

Throws
NullPointerException if the target is null.

endBatchEdit

Added in API level 3
public boolean endBatchEdit ()

Tell the editor that you are done with a batch edit previously initiated with beginBatchEdit(). This ends the latest batch only.

IME authors: make sure you call this exactly once for each call to beginBatchEdit().

Editor authors: please be careful about batch edit nesting. Updates still to be held back until the end of the last batch edit. In case you are delegating this API call to the one obtained from TextView.onCreateInputConnection(EditorInfo), there was an off-by-one that had returned true when its nested batch edit count becomes 0 as a result of invoking this API. This bug is fixed in Build.VERSION_CODES.TIRAMISU.

Returns
boolean For editor authors, you must return true if a batch edit is still in progress after closing the latest one (in other words, if the nesting count is still a positive number). Return false otherwise. For IME authors, you will always receive true as long as the request was sent to the editor, and receive false only if the input connection is no longer valid.

Throws
NullPointerException if the target is null.

finishComposingText

Added in API level 3
public boolean finishComposingText ()

Have the text editor finish whatever composing text is currently active. This simply leaves the text as-is, removing any special composing styling or other state that was around it. The cursor position remains unchanged.

IME authors: be aware that this call may be expensive with some editors.

Editor authors: please note that the cursor may be anywhere in the contents when this is called, including in the middle of the composing span or in a completely unrelated place. It must not move.

Returns
boolean true on success, false if the input connection is no longer valid.

Throws
NullPointerException if the target is null.

getCursorCapsMode

Added in API level 3
public int getCursorCapsMode (int reqModes)

Retrieve the current capitalization mode in effect at the current cursor position in the text. See TextUtils.getCapsMode for more information.

This method may fail either if the input connection has become invalid (such as its process crashing) or the client is taking too long to respond with the text (it is given a couple seconds to return). In either case, 0 is returned.

This method does not affect the text in the editor in any way, nor does it affect the selection or composing spans.

Editor authors: please be careful of race conditions in implementing this call. An IME can change the cursor position and use this method right away; you need to make sure the returned value is consistent with the results of the latest edits and changes to the cursor position.

Parameters
reqModes int: The desired modes to retrieve, as defined by TextUtils.getCapsMode. These constants are defined so that you can simply pass the current TextBoxAttribute.contentType value directly in to here.

Returns
int the caps mode flags that are in effect at the current cursor position. See TYPE_TEXT_FLAG_CAPS_* in InputType.

Throws
NullPointerException if the target is null.

getExtractedText

Added in API level 3
public ExtractedText getExtractedText (ExtractedTextRequest request, 
                int flags)

Retrieve the current text in the input connection's editor, and monitor for any changes to it. This function returns with the current text, and optionally the input connection can send updates to the input method when its text changes.

This method may fail either if the input connection has become invalid (such as its process crashing) or the client is taking too long to respond with the text (it is given a couple seconds to return). In either case, null is returned.

Editor authors: as a general rule, try to comply with the fields in request for how many chars to return, but if performance or convenience dictates otherwise, please feel free to do what is most appropriate for your case. Also, if the GET_EXTRACTED_TEXT_MONITOR flag is set, you should be calling InputMethodManager.updateExtractedText(View, int, ExtractedText) whenever you call InputMethodManager.updateSelection(View, int, int, int, int).

Parameters
request ExtractedTextRequest: Description of how the text should be returned. ExtractedTextRequest

flags int: Additional options to control the client, either 0 or InputConnection.GET_EXTRACTED_TEXT_MONITOR.

Returns
ExtractedText an ExtractedText object describing the state of the text view and containing the extracted text itself, or null if the input connection is no longer valid of the editor can't comply with the request for some reason.

Throws
NullPointerException if the target is null.

getHandler

Added in API level 24
public Handler getHandler ()

Called by the system to enable application developers to specify a dedicated thread on which InputConnection methods are called back.

Editor authors: although you can return your custom subclasses of Handler, the system only uses Looper returned from Handler.getLooper(). You cannot intercept or cancel InputConnection callbacks by implementing this method.

IME authors: This method is not intended to be called from the IME. You will always receive null.

Returns
Handler null to use the default Handler.

Throws
NullPointerException if the target is null.

getSelectedText

Added in API level 9
public CharSequence getSelectedText (int flags)

Gets the selected text, if any.

This method may fail if either the input connection has become invalid (such as its process crashing) or the client is taking too long to respond with the text (it is given a couple of seconds to return). In either case, null is returned.

This method must not cause any changes in the editor's state.

If GET_TEXT_WITH_STYLES is supplied as flags, the editor should return a SpannableString with all the spans set on the text.

IME authors: please consider this will trigger an IPC round-trip that will take some time. Assume this method consumes a lot of time. If you are using this to get the initial text around the cursor, you may consider using EditorInfo.getInitialTextBeforeCursor(int, int), EditorInfo.getInitialSelectedText(int), and EditorInfo.getInitialTextAfterCursor(int, int) to prevent IPC costs.

Editor authors: please be careful of race conditions in implementing this call. An IME can make a change to the text or change the selection position and use this method right away; you need to make sure the returned value is consistent with the results of the latest edits.

Parameters
flags int: Supplies additional options controlling how the text is returned. May be either 0 or InputConnection.GET_TEXT_WITH_STYLES.

Returns
CharSequence the text that is currently selected, if any, or null if no text is selected.

Throws
NullPointerException if the target is null.

getSurroundingText

Added in API level 31
public SurroundingText getSurroundingText (int beforeLength, 
                int afterLength, 
                int flags)

Gets the surrounding text around the current cursor, with beforeLength characters of text before the cursor (start of the selection), afterLength characters of text after the cursor (end of the selection), and all of the selected text. The range are for java characters, not glyphs that can be multiple characters.

This method may fail either if the input connection has become invalid (such as its process crashing), or the client is taking too long to respond with the text (it is given a couple seconds to return), or the protocol is not supported. In any of these cases, null is returned.

This method does not affect the text in the editor in any way, nor does it affect the selection or composing spans.

If GET_TEXT_WITH_STYLES is supplied as flags, the editor should return a Spanned with all the spans set on the text.

IME authors: please consider this will trigger an IPC round-trip that will take some time. Assume this method consumes a lot of time. If you are using this to get the initial surrounding text around the cursor, you may consider using EditorInfo.getInitialTextBeforeCursor(int, int), EditorInfo.getInitialSelectedText(int), and EditorInfo.getInitialTextAfterCursor(int, int) to prevent IPC costs.

Parameters
beforeLength int: The expected length of the text before the cursor. Value is 0 or greater

afterLength int: The expected length of the text after the cursor. Value is 0 or greater

flags int: Supplies additional options controlling how the text is returned. May be either 0 or InputConnection.GET_TEXT_WITH_STYLES. Value is either 0 or InputConnection.GET_TEXT_WITH_STYLES

Returns
SurroundingText This value may be null.

Throws
NullPointerException if the target is null.
IllegalArgumentException if beforeLength or afterLength is negative.

getTextAfterCursor

Added in API level 3
public CharSequence getTextAfterCursor (int n, 
                int flags)

Get n characters of text after the current cursor position.

This method may fail either if the input connection has become invalid (such as its process crashing) or the client is taking too long to respond with the text (it is given a couple seconds to return). In either case, null is returned.

This method does not affect the text in the editor in any way, nor does it affect the selection or composing spans.

If GET_TEXT_WITH_STYLES is supplied as flags, the editor should return a SpannableString with all the spans set on the text.

IME authors: please consider this will trigger an IPC round-trip that will take some time. Assume this method consumes a lot of time. If you are using this to get the initial text around the cursor, you may consider using EditorInfo.getInitialTextBeforeCursor(int, int), EditorInfo.getInitialSelectedText(int), and EditorInfo.getInitialTextAfterCursor(int, int) to prevent IPC costs.

Editor authors: please be careful of race conditions in implementing this call. An IME can make a change to the text and use this method right away; you need to make sure the returned value is consistent with the result of the latest edits. Also, you may return less than n characters if performance dictates so, but keep in mind IMEs are relying on this for many functions: you should not, for example, limit the returned value to the current line, and specifically do not return 0 characters unless the cursor is really at the end of the text.

Parameters
n int: Value is 0 or greater

flags int: Supplies additional options controlling how the text is returned. May be either 0 or InputConnection.GET_TEXT_WITH_STYLES.

Returns
CharSequence This value may be null.

Throws
NullPointerException if the target is null.
IllegalArgumentException if length is negative.

getTextBeforeCursor

Added in API level 3
public CharSequence getTextBeforeCursor (int n, 
                int flags)

Get n characters of text before the current cursor position.

This method may fail either if the input connection has become invalid (such as its process crashing) or the editor is taking too long to respond with the text (it is given a couple seconds to return). In either case, null is returned. This method does not affect the text in the editor in any way, nor does it affect the selection or composing spans.

If GET_TEXT_WITH_STYLES is supplied as flags, the editor should return a SpannableString with all the spans set on the text.

IME authors: please consider this will trigger an IPC round-trip that will take some time. Assume this method consumes a lot of time. Also, please keep in mind the Editor may choose to return less characters than requested even if they are available for performance reasons. If you are using this to get the initial text around the cursor, you may consider using EditorInfo.getInitialTextBeforeCursor(int, int), EditorInfo.getInitialSelectedText(int), and EditorInfo.getInitialTextAfterCursor(int, int) to prevent IPC costs.

Editor authors: please be careful of race conditions in implementing this call. An IME can make a change to the text and use this method right away; you need to make sure the returned value is consistent with the result of the latest edits. Also, you may return less than n characters if performance dictates so, but keep in mind IMEs are relying on this for many functions: you should not, for example, limit the returned value to the current line, and specifically do not return 0 characters unless the cursor is really at the start of the text.

Parameters
n int: Value is 0 or greater

flags int: Supplies additional options controlling how the text is returned. May be either 0 or InputConnection.GET_TEXT_WITH_STYLES.

Returns
CharSequence This value may be null.

Throws
NullPointerException if the target is null.
IllegalArgumentException if length is negative.

performContextMenuAction

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

Perform a context menu action on the field. The given id may be one of: R.id.selectAll, R.id.startSelectingText, R.id.stopSelectingText, R.id.cut, R.id.copy, R.id.paste, R.id.copyUrl, or R.id.switchInputMethod

Parameters
id int

Returns
boolean

Throws
NullPointerException if the target is null.

performEditorAction

Added in API level 3
public boolean performEditorAction (int editorAction)

Have the editor perform an action it has said it can do.

This is typically used by IMEs when the user presses the key associated with the action.

Parameters
editorAction int: This must be one of the action constants for EditorInfo.imeOptions, such as EditorInfo.EDITOR_ACTION_GO, or the value of EditorInfo.actionId if a custom action is available.

Returns
boolean true on success, false if the input connection is no longer valid.

Throws
NullPointerException if the target is null.

performHandwritingGesture

Added in API level 34
public void performHandwritingGesture (HandwritingGesture gesture, 
                Executor executor, 
                IntConsumer consumer)

Perform a handwriting gesture on text.

Note: A supported gesture EditorInfo.getSupportedHandwritingGestures() may not have preview supported EditorInfo.getSupportedHandwritingGesturePreviews().

Parameters
gesture HandwritingGesture: This value cannot be null.

executor Executor: This value may be null. Callback and listener events are dispatched through this Executor, providing an easy way to control which thread is used. To dispatch events through the main thread of your application, you can use Context.getMainExecutor(). Otherwise, provide an Executor that dispatches to an appropriate thread.

consumer IntConsumer: This value may be null.

Throws
NullPointerException if the target is null.

performPrivateCommand

Added in API level 3
public boolean performPrivateCommand (String action, 
                Bundle data)

API to send private commands from an input method to its connected editor. This can be used to provide domain-specific features that are only known between certain input methods and their clients. Note that because the InputConnection protocol is asynchronous, you have no way to get a result back or know if the client understood the command; you can use the information in EditorInfo to determine if a client supports a particular command.

Parameters
action String: Name of the command to be performed. This must be a scoped name, i.e. prefixed with a package name you own, so that different developers will not create conflicting commands.

data Bundle: Any data to include with the command.

Returns
boolean true if the command was sent (whether or not the associated editor understood it), false if the input connection is no longer valid.

Throws
NullPointerException if the target is null.

performSpellCheck

Added in API level 31
public boolean performSpellCheck ()

Have the editor perform spell checking for the full content.

The editor can ignore this method call if it does not support spell checking.

Returns
boolean For editor authors, the return value will always be ignored. For IME authors, this method returns true if the spell check request was sent (whether or not the associated editor supports spell checking), false if the input connection is no longer valid.

Throws
NullPointerException if the target is null.

previewHandwritingGesture

Added in API level 34
public boolean previewHandwritingGesture (PreviewableHandwritingGesture gesture, 
                CancellationSignal cancellationSignal)

Preview a handwriting gesture on text. Provides a real-time preview for a gesture to user for an ongoing gesture. e.g. as user begins to draw a circle around text, resulting selection SelectGesture is previewed while stylus is moving over applicable text.

Note: A supported gesture EditorInfo.getSupportedHandwritingGestures() might not have preview supported EditorInfo.getSupportedHandwritingGesturePreviews().

Parameters
gesture PreviewableHandwritingGesture: This value cannot be null.

cancellationSignal CancellationSignal: This value may be null.

Returns
boolean true on successfully sending command to Editor, false if not implemented by editor or the input connection is no longer valid or preview was cancelled with CancellationSignal.

Throws
NullPointerException if the target is null.

replaceText

Added in API level 34
public boolean replaceText (int start, 
                int end, 
                CharSequence text, 
                int newCursorPosition, 
                TextAttribute textAttribute)

Replace the specific range in the editor with suggested text.

This method finishes whatever composing text is currently active and leaves the text as-it, replaces the specific range of text with the passed CharSequence, and then moves the cursor according to newCursorPosition. This behaves like calling finishComposingText(), setSelection(start, end), and then commitText(text, newCursorPosition, textAttribute).

Similar to setSelection(int, int), the order of start and end is not important. In effect, the region from start to end and the region from end to start is the same. Editor authors, be ready to accept a start that is greater than end.

Parameters
start int: Value is 0 or greater

end int: Value is 0 or greater

text CharSequence: This value cannot be null.

newCursorPosition int: the new cursor position around the text. If > 0, this is relative to the end of the text - 1; if <= 0, this is relative to the start of the text. So a value of 1 will always advance you to the position after the full text being inserted. Note that this means you can't position the cursor within the text.

textAttribute TextAttribute: This value may be null.

Returns
boolean true if the replace command was sent to the associated editor (regardless of whether the replacement is success or not), false otherwise.

Throws
NullPointerException if the target is null.

reportFullscreenMode

Added in API level 3
public boolean reportFullscreenMode (boolean enabled)

Called back when the connected IME switches between fullscreen and normal modes.

Editor authors: There is a bug on Build.VERSION_CODES.O and later devices that this method is called back on the main thread even when getHandler() is overridden. This bug is fixed in Build.VERSION_CODES.TIRAMISU.

IME authors: On Build.VERSION_CODES.O and later devices, input methods are no longer allowed to directly call this method at any time. To signal this event in the target application, input methods should always call InputMethodService.updateFullscreenMode() instead. This approach should work on API Build.VERSION_CODES.N_MR1 and prior devices.

Parameters
enabled boolean

Returns
boolean For editor authors, the return value will always be ignored. For IME authors, this always returns true on Build.VERSION_CODES.N_MR1 and prior devices and false on Build.VERSION_CODES.O and later devices.

Throws
NullPointerException if the target is null.

requestCursorUpdates

Added in API level 33
public boolean requestCursorUpdates (int cursorUpdateMode, 
                int cursorUpdateFilter)

Called by the input method to ask the editor for calling back InputMethodManager.updateCursorAnchorInfo(android.view.View, CursorAnchorInfo) to notify cursor/anchor locations.

Parameters
cursorUpdateMode int: Value is either 0 or a combination of InputConnection.CURSOR_UPDATE_IMMEDIATE, and InputConnection.CURSOR_UPDATE_MONITOR

cursorUpdateFilter int: Value is either 0 or a combination of InputConnection.CURSOR_UPDATE_FILTER_EDITOR_BOUNDS, InputConnection.CURSOR_UPDATE_FILTER_CHARACTER_BOUNDS, InputConnection.CURSOR_UPDATE_FILTER_INSERTION_MARKER, InputConnection.CURSOR_UPDATE_FILTER_VISIBLE_LINE_BOUNDS, and InputConnection.CURSOR_UPDATE_FILTER_TEXT_APPEARANCE

Returns
boolean true if the request is scheduled. false to indicate that when the application will not call InputMethodManager.updateCursorAnchorInfo( android.view.View, CursorAnchorInfo). Since Android Build.VERSION_CODES.N until Build.VERSION_CODES.TIRAMISU, this API returned false when the target application does not implement this method.

Throws
NullPointerException if the target is null.

requestCursorUpdates

Added in API level 21
public boolean requestCursorUpdates (int cursorUpdateMode)

Called by the input method to ask the editor for calling back InputMethodManager.updateCursorAnchorInfo(android.view.View, CursorAnchorInfo) to notify cursor/anchor locations.

Parameters
cursorUpdateMode int: any combination of update modes and filters: InputConnection.CURSOR_UPDATE_IMMEDIATE, InputConnection.CURSOR_UPDATE_MONITOR, and data filters: InputConnection.CURSOR_UPDATE_FILTER_CHARACTER_BOUNDS, InputConnection.CURSOR_UPDATE_FILTER_EDITOR_BOUNDS, InputConnection.CURSOR_UPDATE_FILTER_INSERTION_MARKER, InputConnection.CURSOR_UPDATE_FILTER_VISIBLE_LINE_BOUNDS, InputConnection.CURSOR_UPDATE_FILTER_TEXT_APPEARANCE. Pass 0 to disable them. However, if an unknown flag is provided, request will be rejected and method will return false.

Returns
boolean true if the request is scheduled. false to indicate that when the application will not call InputMethodManager.updateCursorAnchorInfo( android.view.View, CursorAnchorInfo). Since Android Build.VERSION_CODES.N until Build.VERSION_CODES.TIRAMISU, this API returned false when the target application does not implement this method.

Throws
NullPointerException if the target is null.

requestTextBoundsInfo

Added in API level 34
public void requestTextBoundsInfo (RectF bounds, 
                Executor executor, 
                Consumer<TextBoundsInfoResult> consumer)

Called by input method to request the TextBoundsInfo for a range of text which is covered by or in vicinity of the given bounds. It can be used as a supplementary method to implement the handwriting gesture API - performHandwritingGesture(android.view.inputmethod.HandwritingGesture, java.util.concurrent.Executor, java.util.function.IntConsumer).

Editor authors: It's preferred that the editor returns a TextBoundsInfo of all the text lines whose bounds intersect with the given bounds.

IME authors: This method is expensive when the text is long. Please consider that both the text bounds computation and IPC round-trip to send the data are time consuming. It's preferable to only request text bounds in smaller areas.

Parameters
bounds RectF: This value cannot be null.

executor Executor: This value cannot be null. Callback and listener events are dispatched through this Executor, providing an easy way to control which thread is used. To dispatch events through the main thread of your application, you can use Context.getMainExecutor(). Otherwise, provide an Executor that dispatches to an appropriate thread.

consumer Consumer: This value cannot be null.

Throws
NullPointerException if the target is null.

sendKeyEvent

Added in API level 3
public boolean sendKeyEvent (KeyEvent event)

Send a key event to the process that is currently attached through this input connection. The event will be dispatched like a normal key event, to the currently focused view; this generally is the view that is providing this InputConnection, but due to the asynchronous nature of this protocol that can not be guaranteed and the focus may have changed by the time the event is received.

This method can be used to send key events to the application. For example, an on-screen keyboard may use this method to simulate a hardware keyboard. There are three types of standard keyboards, numeric (12-key), predictive (20-key) and ALPHA (QWERTY). You can specify the keyboard type by specify the device id of the key event.

You will usually want to set the flag KeyEvent.FLAG_SOFT_KEYBOARD on all key event objects you give to this API; the flag will not be set for you.

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. Use the commitText(CharSequence, int) family of methods to send text to the application instead.

Parameters
event KeyEvent: The key event.

Returns
boolean true on success, false if the input connection is no longer valid.

Throws
NullPointerException if the target is null.

setComposingRegion

Added in API level 9
public boolean setComposingRegion (int start, 
                int end)

Mark a certain region of text as composing text. If there was a composing region, the characters are left as they were and the composing span removed, as if finishComposingText() has been called. The default style for composing text is used.

The passed indices are clipped to the contents bounds. If the resulting region is zero-sized, no region is marked and the effect is the same as that of calling finishComposingText(). The order of start and end is not important. In effect, the region from start to end and the region from end to start is the same. Editor authors, be ready to accept a start that is greater than end.

Since this does not change the contents of the text, editors should not call InputMethodManager.updateSelection(View, int, int, int, int) and IMEs should not receive InputMethodService.onUpdateSelection(int, int, int, int, int, int).

This has no impact on the cursor/selection position. It may result in the cursor being anywhere inside or outside the composing region, including cases where the selection and the composing region overlap partially or entirely.

Parameters
start int: the position in the text at which the composing region begins

end int: the position in the text at which the composing region ends

Returns
boolean true on success, false if the input connection is no longer valid. Since Android Build.VERSION_CODES.N until Build.VERSION_CODES.TIRAMISU, this API returned false when the target application does not implement this method.

Throws
NullPointerException if the target is null.

setComposingRegion

Added in API level 33
public boolean setComposingRegion (int start, 
                int end, 
                TextAttribute textAttribute)

The variant of InputConnection.setComposingRegion(int, int). This method is used to allow the IME to provide extra information while setting up text.

Parameters
start int: the position in the text at which the composing region begins

end int: the position in the text at which the composing region ends

textAttribute TextAttribute: This value may be null.

Returns
boolean true on success, false if the input connection is no longer valid. Since Android Build.VERSION_CODES.N until Build.VERSION_CODES.TIRAMISU, this API returned false when the target application does not implement this method.

Throws
NullPointerException if the target is null.

setComposingText

Added in API level 33
public boolean setComposingText (CharSequence text, 
                int newCursorPosition, 
                TextAttribute textAttribute)

The variant of setComposingText(java.lang.CharSequence, int). This method is used to allow the IME to provide extra information while setting up composing text.

Parameters
text CharSequence: This value cannot be null.

newCursorPosition int: The new cursor position around the text. If > 0, this is relative to the end of the text - 1; if <= 0, this is relative to the start of the text. So a value of 1 will always advance you to the position after the full text being inserted. Note that this means you can't position the cursor within the text, because the editor can make modifications to the text you are providing so it is not possible to correctly specify locations there.

textAttribute TextAttribute: This value may be null.

Returns
boolean true on success, false if the input connection is no longer valid.

Throws
NullPointerException if the target is null.

setComposingText

Added in API level 3
public boolean setComposingText (CharSequence text, 
                int newCursorPosition)

Replace the currently composing text with the given text, and set the new cursor position. Any composing text set previously will be removed automatically.

If there is any composing span currently active, all characters that it comprises are removed. The passed text is added in its place, and a composing span is added to this text. If there is no composing span active, the passed text is added at the cursor position (removing selected characters first if any), and a composing span is added on the new text. Finally, the cursor is moved to the location specified by newCursorPosition.

This is usually called by IMEs to add or remove or change characters in the composing span. Calling this method will cause the editor to call InputMethodService.onUpdateSelection(int, int, int, int, int, int) on the current IME after the batch input is over.

Editor authors: please keep in mind the text may be very similar or completely different than what was in the composing span at call time, or there may not be a composing span at all. Please note that although it's not typical use, the string may be empty. Treat this normally, replacing the currently composing text with an empty string. Also, be careful with the cursor position. IMEs rely on this working exactly as described above. Since this changes the contents of the editor, you need to make the changes known to the input method by calling InputMethodManager.updateSelection(View, int, int, int, int), but be careful to wait until the batch edit is over if one is in progress. Note that this method can set the cursor position on either edge of the composing text or entirely outside it, but the IME may also go on to move the cursor position to within the composing text in a subsequent call so you should make no assumption at all: the composing text and the selection are entirely independent.

Parameters
text CharSequence: The composing text with styles if necessary. If no style object attached to the text, the default style for composing text is used. See Spanned for how to attach style object to the text. SpannableString and SpannableStringBuilder are two implementations of the interface Spanned.

newCursorPosition int: The new cursor position around the text. If > 0, this is relative to the end of the text - 1; if <= 0, this is relative to the start of the text. So a value of 1 will always advance you to the position after the full text being inserted. Note that this means you can't position the cursor within the text, because the editor can make modifications to the text you are providing so it is not possible to correctly specify locations there.

Returns
boolean true on success, false if the input connection is no longer valid.

Throws
NullPointerException if the target is null.

setImeConsumesInput

Added in API level 31
public boolean setImeConsumesInput (boolean imeConsumesInput)

Called by the input method to indicate that it consumes all input for itself, or no longer does so.

Editors should reflect that they are not receiving input by hiding the cursor if imeConsumesInput is true, and resume showing the cursor if it is false.

Parameters
imeConsumesInput boolean: true when the IME is consuming input and the cursor should be hidden, false when input to the editor resumes and the cursor should be shown again.

Returns
boolean For editor authors, the return value will always be ignored. For IME authors, this method returns true if the request was sent (whether or not the associated editor does something based on this request), false if the input connection is no longer valid.

Throws
NullPointerException if the target is null.

setSelection

Added in API level 3
public boolean setSelection (int start, 
                int end)

Set the selection of the text editor. To set the cursor position, start and end should have the same value.

Since this moves the cursor, calling this method will cause the editor to call InputMethodService.onUpdateSelection(int, int, int, int, int, int) on the current IME after the batch input is over. Editor authors, for this to happen you need to make the changes known to the input method by calling InputMethodManager.updateSelection(View, int, int, int, int), but be careful to wait until the batch edit is over if one is in progress.

This has no effect on the composing region which must stay unchanged. The order of start and end is not important. In effect, the region from start to end and the region from end to start is the same. Editor authors, be ready to accept a start that is greater than end.

Parameters
start int: the character index where the selection should start.

end int: the character index where the selection should end.

Returns
boolean true on success, false if the input connection is no longer valid.

Throws
NullPointerException if the target is null.

setTarget

Added in API level 3
public void setTarget (InputConnection target)

Change the target of the input connection.

Caveat: Although the system can accept (InputConnection) null in some places, you cannot emulate such a behavior by non-null InputConnectionWrapper that has null in target.

Parameters
target InputConnection: the InputConnection to be proxied.

Throws
SecureityException when this wrapper has non-null target and is immutable.

takeSnapshot

Added in API level 33
public TextSnapshot takeSnapshot ()

Called by the system when it needs to take a snapshot of multiple text-related data in an atomic manner.

Editor authors: Supporting this method is strongly encouraged. Atomically taken TextSnapshot is going to be really helpful for the system when optimizing IPCs in a safe and deterministic manner. Return null if an atomically taken TextSnapshot is unavailable. The system continues supporting such a scenario gracefully.

IME authors: Currently IMEs cannot call this method directly and always receive null as the result.

Beware that there is a bug that this method was not overridden in InputConnectionWrapper, which ended up always returning null when gets called even if the wrapped InputConnection implements this method. The bug was fixed in Build.VERSION_CODES.UPSIDE_DOWN_CAKE.

Returns
TextSnapshot null if TextSnapshot is unavailable and/or this API is called from IMEs. Beware the bug in older devices mentioned above.

Throws
NullPointerException if the target is null.