InputConnection
public
interface
InputConnection
| android.view.inputmethod.InputConnection |
The InputConnection interface is the communication channel from an
InputMethod back to the application that is receiving its
input. It is used to perform such things as reading text around the
cursor, committing text to the text box, and sending raw key events
to the application.
Starting from API Level Build.VERSION_CODES.N,
the system can deal with the situation where the application directly
implements this class but one or more of the following methods are
not implemented.
getSelectedText(int), which was introduced inBuild.VERSION_CODES.GINGERBREAD.setComposingRegion(int, int), which was introduced inBuild.VERSION_CODES.GINGERBREAD.commitCorrection(CorrectionInfo), which was introduced inBuild.VERSION_CODES.HONEYCOMB.requestCursorUpdates(int), which was introduced inBuild.VERSION_CODES.LOLLIPOP.deleteSurroundingTextInCodePoints(int, int), which was introduced inBuild.VERSION_CODES.N.getHandler(), which was introduced inBuild.VERSION_CODES.N.closeConnection(), which was introduced inBuild.VERSION_CODES.N.commitContent(InputContentInfo,int,Bundle), which was introduced inBuild.VERSION_CODES.N_MR1.
Implementing an IME or an editor
Text input is the result of the synergy of two essential components:
an Input Method Engine (IME) and an editor. The IME can be a
software keyboard, a handwriting interface, an emoji palette, a
speech-to-text engine, and so on. There are typically several IMEs
installed on any given Android device. In Android, IMEs extend
InputMethodService.
For more information about how to create an IME, see the
Creating an input method guide.
The editor is the component that receives text and displays it.
Typically, this is an EditText instance, but
some applications may choose to implement their own editor for
various reasons. This is a large and complicated task, and an
application that does this needs to make sure the behavior is
consistent with standard EditText behavior in Android. An editor
needs to interact with the IME, receiving commands through
this InputConnection interface, and sending commands through
InputMethodManager. An editor
should start by implementing
android.view.View.onCreateInputConnection(EditorInfo)
to return its own input connection.
If you are implementing your own IME, you will need to call the methods in this interface to interact with the application. Be sure to test your IME with a wide range of applications, including browsers and rich text editors, as some may have peculiarities you need to deal with. Remember your IME may not be the only source of changes on the text, and try to be as conservative as possible in the data you send and as liberal as possible in the data you receive.
If you are implementing your own editor, you will probably need
to provide your own subclass of BaseInputConnection to
answer to the commands from IMEs. Please be sure to test your
editor with as many IMEs as you can as their behavior can vary a
lot. Also be sure to test with various languages, including CJK
languages and right-to-left languages like Arabic, as these may
have different input requirements. When in doubt about the
behavior you should adopt for a particular call, please mimic the
default TextView implementation in the latest Android version, and
if you decide to drift from it, please consider carefully that
inconsistencies in text editor behavior is almost universally felt
as a bad thing by users.
Cursors, selections and compositions
In Android, the cursor and the selection are one and the same thing. A "cursor" is just the special case of a zero-sized selection. As such, this documentation uses them interchangeably. Any method acting "before the cursor" would act before the start of the selection if there is one, and any method acting "after the cursor" would act after the end of the selection.
An editor needs to be able to keep track of a currently
"composing" region, like the standard edition widgets do. The
composition is marked in a specific style: see
Spanned.SPAN_COMPOSING. IMEs use this to help
the user keep track of what part of the text they are currently
focusing on, and interact with the editor using
InputConnection.setComposingText(CharSequence,int),
InputConnection.setComposingRegion(int,int) and
InputConnection.finishComposingText().
The composing region and the selection are completely independent
of each other, and the IME may use them however they see fit.
Summary
Public methods | |
|---|---|
abstract
boolean
|
beginBatchEdit()
Tell the editor that you are starting a batch of editor operations. |
abstract
boolean
|
clearMetaKeyStates(int states)
Clear the given meta key pressed states in the given input connection. |
abstract
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. |
abstract
boolean
|
commitCompletion(CompletionInfo text)
Commit a completion the user has selected from the possible ones
previously reported to |
abstract
boolean
|
commitContent(InputContentInfo inputContentInfo, int flags, Bundle opts)
Called by the input method to commit content such as a PNG image to the editor. |
abstract
boolean
|
commitCorrection(CorrectionInfo correctionInfo)
Commit a correction automatically performed on the raw user's input. |
default
boolean
|
commitText(CharSequence text, int newCursorPosition, TextAttribute textAttribute)
The variant of |
abstract
boolean
|
commitText(CharSequence text, int newCursorPosition)
Commit text to the text box and set the new cursor position. |
abstract
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. |
abstract
boolean
|
deleteSurroundingTextInCodePoints(int beforeLength, int afterLength)
A variant of |
abstract
boolean
|
endBatchEdit()
Tell the editor that you are done with a batch edit previously initiated with
|
abstract
boolean
|
finishComposingText()
Have the text editor finish whatever composing text is currently active. |
abstract
int
|
getCursorCapsMode(int reqModes)
Retrieve the current capitalization mode in effect at the current cursor position in the text. |
abstract
ExtractedText
|
getExtractedText(ExtractedTextRequest request, int flags)
Retrieve the current text in the input connection's editor, and monitor for any changes to it. |
abstract
Handler
|
getHandler()
Called by the system to enable application developers to specify a dedicated thread on which
|
abstract
CharSequence
|
getSelectedText(int flags)
Gets the selected text, if any. |
default
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. |
abstract
CharSequence
|
getTextAfterCursor(int n, int flags)
Get n characters of text after the current cursor position. |
abstract
CharSequence
|
getTextBeforeCursor(int n, int flags)
Get n characters of text before the current cursor position. |
abstract
boolean
|
performContextMenuAction(int id)
Perform a context menu action on the field. |
abstract
boolean
|
performEditorAction(int editorAction)
Have the editor perform an action it has said it can do. |
default
void
|
performHandwritingGesture(HandwritingGesture gesture, Executor executor, IntConsumer consumer)
Perform a handwriting gesture on text. |
abstract
boolean
|
performPrivateCommand(String action, Bundle data)
API to send private commands from an input method to its connected editor. |
default
boolean
|
performSpellCheck()
Have the editor perform spell checking for the full content. |
default
boolean
|
previewHandwritingGesture(PreviewableHandwritingGesture gesture, CancellationSignal cancellationSignal)
Preview a handwriting gesture on text. |
default
boolean
|
replaceText(int start, int end, CharSequence text, int newCursorPosition, TextAttribute textAttribute)
Replace the specific range in the editor with suggested text. |
abstract
boolean
|
reportFullscreenMode(boolean enabled)
Called back when the connected IME switches between fullscreen and normal modes. |
default
boolean
|
requestCursorUpdates(int cursorUpdateMode, int cursorUpdateFilter)
Called by the input method to ask the editor for calling back
|
abstract
boolean
|
requestCursorUpdates(int cursorUpdateMode)
Called by the input method to ask the editor for calling back
|
default
void
|
)">requestTextBoundsInfo(RectF bounds, Executor executor, Consumer<TextBoundsInfoResult> consumer)
Called by input method to request the |
abstract
boolean
|
sendKeyEvent(KeyEvent event)
Send a key event to the process that is currently attached through this input connection. |
abstract
boolean
|
setComposingRegion(int start, int end)
Mark a certain region of text as composing text. |
default
boolean
|
setComposingRegion(int start, int end, TextAttribute textAttribute)
The variant of |
default
boolean
|
setComposingText(CharSequence text, int newCursorPosition, TextAttribute textAttribute)
The variant of |
abstract
boolean
|
setComposingText(CharSequence text, int newCursorPosition)
Replace the currently composing text with the given text, and set the new cursor position. |
default
boolean
|
setImeConsumesInput(boolean imeConsumesInput)
Called by the input method to indicate that it consumes all input for itself, or no longer does so. |
abstract
boolean
|
setSelection(int start, int end)
Set the selection of the text editor. |
default
TextSnapshot
|
takeSnapshot()
Called by the system when it needs to take a snapshot of multiple text-related data in an atomic manner. |
Constants
CURSOR_UPDATE_FILTER_CHARACTER_BOUNDS
public static final int CURSOR_UPDATE_FILTER_CHARACTER_BOUNDS
The editor is requested to call
InputMethodManager.updateCursorAnchorInfo(android.view.View,CursorAnchorInfo)
with new character bounds CursorAnchorInfo.getCharacterBounds(int) whenever
cursor/anchor position is changed. To disable
monitoring, call InputConnection.requestCursorUpdates(int) again with this flag off.
This flag can be combined with other filters: CURSOR_UPDATE_FILTER_EDITOR_BOUNDS,
CURSOR_UPDATE_FILTER_VISIBLE_LINE_BOUNDS,
CURSOR_UPDATE_FILTER_TEXT_APPEARANCE, CURSOR_UPDATE_FILTER_INSERTION_MARKER
and update flags CURSOR_UPDATE_IMMEDIATE and CURSOR_UPDATE_MONITOR.
Constant Value: 8 (0x00000008)
CURSOR_UPDATE_FILTER_EDITOR_BOUNDS
public static final int CURSOR_UPDATE_FILTER_EDITOR_BOUNDS
The editor is requested to call
InputMethodManager.updateCursorAnchorInfo(android.view.View,CursorAnchorInfo)
with new EditorBoundsInfo whenever cursor/anchor position is changed. To disable
monitoring, call InputConnection.requestCursorUpdates(int) again with this flag off.
This flag can be used together with filters: CURSOR_UPDATE_FILTER_CHARACTER_BOUNDS,
CURSOR_UPDATE_FILTER_VISIBLE_LINE_BOUNDS,
CURSOR_UPDATE_FILTER_TEXT_APPEARANCE,
CURSOR_UPDATE_FILTER_INSERTION_MARKER and update flags
CURSOR_UPDATE_IMMEDIATE and CURSOR_UPDATE_MONITOR.
Constant Value: 4 (0x00000004)
CURSOR_UPDATE_FILTER_INSERTION_MARKER
public static final int CURSOR_UPDATE_FILTER_INSERTION_MARKER
The editor is requested to call
InputMethodManager.updateCursorAnchorInfo(android.view.View,CursorAnchorInfo)
with new Insertion marker info CursorAnchorInfo.getInsertionMarkerFlags(),
CursorAnchorInfo.getInsertionMarkerBaseline(), etc whenever cursor/anchor position is
changed. To disable monitoring, call InputConnection.requestCursorUpdates(int) again
with this flag off.
This flag can be combined with other filters: CURSOR_UPDATE_FILTER_CHARACTER_BOUNDS,
CURSOR_UPDATE_FILTER_VISIBLE_LINE_BOUNDS,
CURSOR_UPDATE_FILTER_TEXT_APPEARANCE, CURSOR_UPDATE_FILTER_EDITOR_BOUNDS
and update flags CURSOR_UPDATE_IMMEDIATE and CURSOR_UPDATE_MONITOR.
Constant Value: 16 (0x00000010)
CURSOR_UPDATE_FILTER_TEXT_APPEARANCE
public static final int CURSOR_UPDATE_FILTER_TEXT_APPEARANCE
The editor is requested to call
InputMethodManager.updateCursorAnchorInfo(android.view.View,CursorAnchorInfo)
with new text appearance info CursorAnchorInfo.getTextAppearanceInfo()}
whenever cursor/anchor position is changed. To disable monitoring, call
InputConnection.requestCursorUpdates(int) again with this flag off.
This flag can be combined with other filters: CURSOR_UPDATE_FILTER_CHARACTER_BOUNDS,
CURSOR_UPDATE_FILTER_EDITOR_BOUNDS, CURSOR_UPDATE_FILTER_INSERTION_MARKER,
CURSOR_UPDATE_FILTER_VISIBLE_LINE_BOUNDS and update flags
CURSOR_UPDATE_IMMEDIATE and CURSOR_UPDATE_MONITOR.
Constant Value: 64 (0x00000040)
CURSOR_UPDATE_FILTER_VISIBLE_LINE_BOUNDS
public static final int CURSOR_UPDATE_FILTER_VISIBLE_LINE_BOUNDS
The editor is requested to call
InputMethodManager.updateCursorAnchorInfo(android.view.View,CursorAnchorInfo)
with new visible line bounds CursorAnchorInfo.getVisibleLineBounds() whenever
cursor/anchor position is changed, the editor or its parent is scrolled or the line bounds
changed due to text updates. To disable monitoring, call
InputConnection.requestCursorUpdates(int) again with this flag off.
This flag can be combined with other filters: CURSOR_UPDATE_FILTER_CHARACTER_BOUNDS,
CURSOR_UPDATE_FILTER_EDITOR_BOUNDS, CURSOR_UPDATE_FILTER_INSERTION_MARKER,
CURSOR_UPDATE_FILTER_TEXT_APPEARANCE and update flags
CURSOR_UPDATE_IMMEDIATE and CURSOR_UPDATE_MONITOR.
Constant Value: 32 (0x00000020)
CURSOR_UPDATE_IMMEDIATE
public static final int CURSOR_UPDATE_IMMEDIATE
The editor is requested to call
InputMethodManager.updateCursorAnchorInfo(android.view.View,CursorAnchorInfo) at
once, as soon as possible, regardless of cursor/anchor position changes. This flag can be
used together with CURSOR_UPDATE_MONITOR.
Note by default all of CURSOR_UPDATE_FILTER_EDITOR_BOUNDS,
CURSOR_UPDATE_FILTER_CHARACTER_BOUNDS,
CURSOR_UPDATE_FILTER_VISIBLE_LINE_BOUNDS,
CURSOR_UPDATE_FILTER_TEXT_APPEARANCE, and
CURSOR_UPDATE_FILTER_INSERTION_MARKER, are included but specifying them can
filter-out others.
It can be CPU intensive to include all, filtering specific info is recommended.
Constant Value: 1 (0x00000001)
CURSOR_UPDATE_MONITOR
public static final int CURSOR_UPDATE_MONITOR
The editor is requested to call
InputMethodManager.updateCursorAnchorInfo(android.view.View,CursorAnchorInfo)
whenever cursor/anchor position is changed. To disable monitoring, call
InputConnection.requestCursorUpdates(int) again with this flag off.
This flag can be used together with CURSOR_UPDATE_IMMEDIATE.
Note by default all of CURSOR_UPDATE_FILTER_EDITOR_BOUNDS,
CURSOR_UPDATE_FILTER_CHARACTER_BOUNDS,
CURSOR_UPDATE_FILTER_VISIBLE_LINE_BOUNDS,
CURSOR_UPDATE_FILTER_TEXT_APPEARANCE, and
CURSOR_UPDATE_FILTER_INSERTION_MARKER, are included but specifying them can
filter-out others.
It can be CPU intensive to include all, filtering specific info is recommended.
Constant Value: 2 (0x00000002)
GET_EXTRACTED_TEXT_MONITOR
public static final int GET_EXTRACTED_TEXT_MONITOR
Flag for use with getExtractedText(ExtractedTextRequest, int) to indicate you
would like to receive updates when the extracted text changes.
Constant Value: 1 (0x00000001)
GET_TEXT_WITH_STYLES
public static final int GET_TEXT_WITH_STYLES
Flag for use with getTextAfterCursor(int, int), getTextBeforeCursor(int, int) and
getSurroundingText(int, int, int) to have style information returned along with the text. If not
set, getTextAfterCursor(int, int) sends only the raw text, without style or other spans. If
set, it may return a complex CharSequence of both text and style spans.
Editor authors: you should strive to send text with styles if possible, but
it is not required.
Constant Value: 1 (0x00000001)
HANDWRITING_GESTURE_RESULT_CANCELLED
public static final int HANDWRITING_GESTURE_RESULT_CANCELLED
Result for performHandwritingGesture(HandwritingGesture,Executor,IntConsumer) when
HandwritingGesture was cancelled. This happens when the InputConnection is
or becomes invalidated while performing the gesture, for example because a new
InputConnection was started, or due to InputMethodManager.invalidateInput.
Constant Value: 4 (0x00000004)
HANDWRITING_GESTURE_RESULT_FAILED
public static final int HANDWRITING_GESTURE_RESULT_FAILED
Result for performHandwritingGesture(HandwritingGesture,Executor,IntConsumer) when
HandwritingGesture failed and there was no applicable
HandwritingGesture.getFallbackText() or it couldn't
be applied for any other reason.
Constant Value: 3 (0x00000003)
HANDWRITING_GESTURE_RESULT_FALLBACK
public static final int HANDWRITING_GESTURE_RESULT_FALLBACK
Result for performHandwritingGesture(HandwritingGesture,Executor,IntConsumer) when
HandwritingGesture failed but HandwritingGesture.getFallbackText() was
committed.
Constant Value: 5 (0x00000005)
HANDWRITING_GESTURE_RESULT_SUCCESS
public static final int HANDWRITING_GESTURE_RESULT_SUCCESS
Result for performHandwritingGesture(HandwritingGesture,Executor,IntConsumer) when
HandwritingGesture is successfully executed on text.
Constant Value: 1 (0x00000001)
HANDWRITING_GESTURE_RESULT_UNKNOWN
public static final int HANDWRITING_GESTURE_RESULT_UNKNOWN
Result for performHandwritingGesture(HandwritingGesture,Executor,IntConsumer) when
editor didn't provide any result.
Constant Value: 0 (0x00000000)
HANDWRITING_GESTURE_RESULT_UNSUPPORTED
public static final int HANDWRITING_GESTURE_RESULT_UNSUPPORTED
Result for performHandwritingGesture(HandwritingGesture,Executor,IntConsumer) when
HandwritingGesture is unsupported by the current editor.
Constant Value: 2 (0x00000002)
INPUT_CONTENT_GRANT_READ_URI_PERMISSION
public static final int INPUT_CONTENT_GRANT_READ_URI_PERMISSION
When this flag is used, the editor will be able to request read access to the content URI
contained in the InputContentInfo object.
Make sure that the content provider owning the Uri sets the
grantUriPermissions attribute in its manifest or included the
<grant-uri-permissions> tag. Otherwise InputContentInfo.requestPermission()
can fail.
Although calling this API is allowed only for the IME that is currently selected, the
client is able to request a temporary read-only access even after the current IME is switched
to any other IME as long as the client keeps InputContentInfo object.
Constant Value: 1 (0x00000001)
Public methods
beginBatchEdit
public abstract 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. |
clearMetaKeyStates
public abstract 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. |
closeConnection
public abstract 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.
commitCompletion
public abstract 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(CharSequence,int).
IME authors: please take care to send the
same object that you received through
android.inputmethodservice.InputMethodService.onDisplayCompletions(CompletionInfo[]).
Editor authors: if you never call
InputMethodSession.displayCompletions(CompletionInfo[]) or
InputMethodManager.displayCompletions(android.view.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(android.view.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. |
commitContent
public abstract 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.contentMimeTypesequal tonullif it does not support this method at all. - Editor can ignore this request when the MIME type specified in
inputContentInfodoes not match any ofEditorInfo.contentMimeTypes. - Editor can ignore the cursor position when inserting the provided content.
- Editor can return
trueasynchronously, 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.packageNameabout how to obtain the package name of the editor.
| Parameters | |
|---|---|
inputContentInfo |
InputContentInfo: Content to be inserted.
This value cannot be null. |
flags |
int: 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. |
commitCorrection
public abstract 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(android.view.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. |
commitText
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: The text to commit. This may include styles.
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 end of the text - 1; if
| |