I have a soft keyboard app. I am trying to getSelectedText()
of the EditText in order to handle occasions when user has selected some text. I need to do this because my app does not access the app views, because it is just the soft keyboard.
However, this operation takes too long to compute sometimes, causing ANRs. I added a timeout, but this is causing new ANRs since it's blocking the main thread.
I've seen in the official documentation this comment by 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.
Can someone help me with this?
Another thing I thought about is running the operation in a background thread. But this doesn't seem right since it's something related to the UI.
What I'm doing is:
CoroutineScope(Dispatchers.Main).launch {
try {
withTimeout(100L) {
inputConnection?.getSelectedText(0)
}
} catch (exception: TimeoutCancellationException) { null }
}.invokeOnCompletion {