Jee*_*van 5 android speech-recognition
在我的应用中,我直接使用SpeechRecognizer.我销毁SpeechRecognizer onPause的活动,我在onResume方法中重新创建它,如下所示...
public class NoUISpeechActivity extends Activity {
protected static final String CLASS_TAG = "NoUISpeechActivity";
private SpeechRecognizer sr;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_no_uispeech);
sr = getSpeechRecognizer();
}
@Override
protected void onPause() {
Log.i(CLASS_TAG, "on pause called");
if(sr!=null){
sr.stopListening();
sr.cancel();
sr.destroy();
}
super.onPause();
}
@Override
protected void onResume() {
Log.i(CLASS_TAG, "on resume called");
sr = getSpeechRecognizer();
super.onResume();
}
....
private SpeechRecognizer getSpeechRecognizer() {
if(sr == null){
sr = SpeechRecognizer.createSpeechRecognizer(getApplicationContext());
CustomRecognizerListner listner = new CustomRecognizerListner();
listner.setOnListeningCallback(new OnListeningCallbackImp());
sr.setRecognitionListener(listner);
}
return sr;
}
}
Run Code Online (Sandbox Code Playgroud)
当应用程序首次通过eclipse安装时,会调用SpeechRecognition服务并正确识别.但是当应用程序从暂停状态恢复时,如果我尝试识别语音,我会收到"SpeechRecognition:not connect to recognition service"错误
我究竟做错了什么 ?
我找到了问题的原因.在onPause方法虽然SpeechRecognition.destroy()调用方法,我猜它只是分离服务但对象sr将指向一些实例,它不会为null.将对象重置sr为null可以解决问题.
不破坏方法中的SpeechRecognition对象onPause会阻止其他应用程序使用SpeechRecognition服务
@Override
protected void onPause() {
Log.i(CLASS_TAG, "on pause called");
if(sr!=null){
sr.stopListening();
sr.cancel();
sr.destroy();
}
sr = null;
super.onPause();
}
Run Code Online (Sandbox Code Playgroud)