在我的应用中,我直接使用SpeechRecognizer。我在Activity的onPause上销毁了SpeechRecognizer,然后在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;
}
}

第一次通过eclipse安装应用程序时,会调用SpeechRecognition服务,并且会正确进行识别。但是当应用程序从暂停返回时,如果我尝试识别语音,则会收到“SpeechRecognition:未连接到识别服务”错误

我究竟做错了什么 ?

最佳答案

我找到了问题的原因。在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();
}

10-06 02:40