0

我正在尝试使用此处提供的代码在服务中运行语音识别 api,但我在这样做时遇到了麻烦。

我的活动有以下几行:

protected void onCreate(Bundle savedInstanceState) {
......

Intent startConstantSR = new Intent("MyService.class");
        getApplicationContext().startService(startConstantSR);
....
}

并且服务的 onCreate 看起来像这样

public void onCreate()
    {super.onCreate();
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); 
        mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
        mSpeechRecognizer.setRecognitionListener(new SpeechRecognitionListener());
        mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                                         RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
                                         this.getPackageName());
      mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
 }

我已经在 onReadyForSpeech 和 onBeginningOfSpeech 中设置了一个 Toast 来显示,所以我知道我走在正确的道路上 - 但没有触发任何 toast。

我究竟做错了什么?我无法找到,因为我对服务几乎不熟悉。

4

1 回答 1

0

You have to either override onStartCommand in the service to send a listening message or bind to the service and send a listening message

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{

    Message msg = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);

    try
    {
        mServerMessenger.send(msg);
    } 
    catch (RemoteException e)
    {

    }
    return START_STICKY;
}

For the bind implementation see Android Speech Recognition Continuous Service

于 2013-08-05T17:36:55.337 回答