Skip to content

Instantly share code, notes, and snippets.

@RadiationX
Last active March 12, 2024 12:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RadiationX/c2997a5f03e1717db22b6603d4ec1e97 to your computer and use it in GitHub Desktop.
Save RadiationX/c2997a5f03e1717db22b6603d4ec1e97 to your computer and use it in GitHub Desktop.
Fix java.lang.IllegalArgumentException: Service not registered: android.speech.SpeechRecognizer$Connection
// 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)
}
}
@RadiationX
Copy link
Author

You can test this on tv/phone/emulator without google services

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment