处理结束或错误情况的一种解决方案是将 a 设置RecognitionListener
为您的SpeechRecognizer
实例。你必须在打电话之前startListening()
做!
例子:
mInternalSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
// Other methods implementation
@Override
public void onEndOfSpeech() {
// Handle end of speech recognition
}
@Override
public void onError(int error) {
// Handle end of speech recognition and error
}
// Other methods implementation
});
在你的情况下,你可以让你的类包含mIsRecording
属性实现RecognitionListener
接口。然后,您只需使用以下指令覆盖这两个方法:
mIsRecording = false;
此外,你的mIsRecording = true
指令是在错误的地方。您应该在onReadyForSpeech(Bundle params)
方法定义中执行此操作,否则,当此值为 true 时,语音识别可能永远不会启动。
最后,在管理它的类中,只需创建如下方法:
// Other RecognitionListener's methods implementation
@Override
public void onEndOfSpeech() {
mIsRecording = false;
}
@Override
public void onError(int error) {
mIsRecording = false;
// Print error
}
@Override
void onReadyForSpeech (Bundle params) {
mIsRecording = true;
}
public void startRecording(Intent intent) {
// ...
mInternalSpeechRecognizer.setRecognitionListener(this);
mInternalSpeechRecognizer.startListening(intent);
}
public boolean recordingIsRunning() {
return mIsRecording;
}
注意记录IsRunning调用的线程安全,一切都会好的:)