androidsamsung-mobile

Samsung Android 13 Keyboard Span ANR and Crashes


Samsung with its special keyboard implementation causes either ANR or crashes within EditText.

ANRs look like

android.text.SpannableStringBuilder.countSpans (SpannableStringBuilder.java:930)
android.text.SpannableStringBuilder.countSpans (SpannableStringBuilder.java:934)
android.text.SpannableStringBuilder.countSpans (SpannableStringBuilder.java:914)
android.text.SpannableStringBuilder.countSpans (SpannableStringBuilder.java:934)
android.text.SpannableStringBuilder.countSpans (SpannableStringBuilder.java:914)
android.text.SpannableStringBuilder.countSpans (SpannableStringBuilder.java:934)
android.text.SpannableStringBuilder.countSpans (SpannableStringBuilder.java:934)
android.text.SpannableStringBuilder.countSpans (SpannableStringBuilder.java:914)
android.text.SpannableStringBuilder.countSpans (SpannableStringBuilder.java:934)
android.text.SpannableStringBuilder.getSpans (SpannableStringBuilder.java:885)
android.text.SpannableStringBuilder.getSpans (SpannableStringBuilder.java:863)
androidx.emoji2.text.SpannableBuilder.getSpans (SpannableBuilder.java:159)

If you're using spans inside your editText Samsung multiplies spans during the editing of text. The number of spans grows exponentially so you'll have ANR in around 15-20 seconds. Basically, every time you click inside your EditText new spans are created. I was able to find that multiplication happens inside SpannableStringBuilder.replace method but can't go through the source code as I think Samsung uses its own implementation.

This may be connected to how suggestions are implemented inside Samsung's keyboard. As I found from https://github.com/facebook/react-native/issues/33139 if you set your input type to 'visible-password' or 'email-address' spans stop multiplying.

But here comes the crashes.

Fatal Exception: java.lang.IndexOutOfBoundsException
setSpan (0 ... -1) has end before start

As far as I can tell crash happens just as you start editing text.

I didn't find a lot of mentions of this issue but pretty sure anyone who uses spans in their codebase is affected. For example, here's Grammarly thread dealing with the same issue - https://github.com/facebook/react-native/issues/35590

So the question does someone was able to find another solution? Are you also struggling with Android 13 Samsung's update?

I'll post any updates if I find any.


Solution

  • The issue was with Grammarly suggestions which are available by default on Samsung's Android 13. Our solution was to use disable suggestions with TYPE_TEXT_FLAG_NO_SUGGESTIONS. It gets rid of ANR and crashes.

        if (Build.MANUFACTURER.equals("samsung", ignoreCase = true)
            && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            inputType = inputType or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
        }