如果您已经授予了RECORD_AUDIO和INTERNET权限,并且SpeechRecognizer在活动中正常工作,则此错误可能是由于SpeechRecognizer正在在服务中运行而引起的。在服务中运行SpeechRecognizer时,需要确保SpeechRecognizer实例的生命周期与服务实例的生命周期相同,并且将SpeechRecognizer的initialize方法放置在服务的onCreate()方法中,而不是在onStartCommand()方法中。以下是示例代码:
public class MyService extends Service { private SpeechRecognizer mSpeechRecognizer;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
// ...
});
boolean isRecognitionAvailable = SpeechRecognizer.isRecognitionAvailable(this);
if (isRecognitionAvailable) {
Intent recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
getApplicationContext().getPackageName());
mSpeechRecognizer.startListening(recognizerIntent);
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (mSpeechRecognizer != null) {
mSpeechRecognizer.destroy();
}
}
}