Last active
March 12, 2024 12:26
-
-
Save RadiationX/c2997a5f03e1717db22b6603d4ec1e97 to your computer and use it in GitHub Desktop.
Fix java.lang.IllegalArgumentException: Service not registered: android.speech.SpeechRecognizer$Connection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// add this to your implementation SearchSupportFragment | |
// put avoidSpeechRecognitinCrash() in your fragment before onPause() | |
override fun onPause() { | |
avoidSpeechRecognitinCrash() | |
super.onPause() | |
} | |
// "destroy" may throw java.lang.IllegalArgumentException: Service not registered: android.speech.SpeechRecognizer$Connection@dabd9b8 | |
// do all this mehod's work and wrap "destroy" to try catch | |
// private void releaseRecognizer() { | |
// if (null != mSpeechRecognizer) { | |
// mSearchBar.setSpeechRecognizer(null); | |
// mSpeechRecognizer.destroy(); | |
// mSpeechRecognizer = null; | |
// } | |
// } | |
private fun avoidSpeechRecognitinCrash() { | |
val mSpeechRecognizerField = | |
SearchSupportFragment::class.java.getDeclaredField("mSpeechRecognizer").apply { | |
isAccessible = true | |
} | |
val mSearchBarField = | |
SearchSupportFragment::class.java.getDeclaredField("mSearchBar").apply { | |
isAccessible = true | |
} | |
val currentSpeechRecognizer = mSpeechRecognizerField.get(this) | |
if (currentSpeechRecognizer != null) { | |
val mSearchBar = mSearchBarField.get(this) | |
val setSpeechRecognizerMethod = mSearchBar::class.java.getDeclaredMethod( | |
"setSpeechRecognizer", | |
SpeechRecognizer::class.java | |
).apply { | |
isAccessible = true | |
} | |
setSpeechRecognizerMethod.invoke(mSearchBar, null) | |
val destroyMethod = currentSpeechRecognizer::class.java.getDeclaredMethod( | |
"destroy" | |
).apply { | |
isAccessible = true | |
} | |
try { | |
destroyMethod.invoke(currentSpeechRecognizer) | |
} catch (ignore: IllegalArgumentException) { | |
// ignore | |
} | |
mSpeechRecognizerField.set(this, null) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can test this on tv/phone/emulator without google services