Recognizer PendingIntent流程的工作示例

时间:2015-01-29 15:35:34

标签: android wear-os android-pendingintent

我有以下代码设置来启动带有pendingintent的语音识别器以启动另一个活动:

Intent voiceActivityIntent = new Intent (MainActivity.this, VoiceActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity (MainActivity.this, 0, 
    voiceActivityIntent, PendingIntent.FLAG_ONE_SHOT);

Intent intent = new Intent (RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
    .putExtra (RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
    .putExtra (RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, pendingIntent);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

文档指出startActivity不能与 RecognizerIntent.ACTION_RECOGNIZE_SPEECH 一起使用,并且使用startActivityForResult只是将结果返回到当前活动(MainActivity),这是不需要的。

我试过了:

pendingIntent.send ();

但这只是带我到VoiceActivity.class而不执行识别器。

我目前正在测试Android Wear Round API 21模拟器。

2 个答案:

答案 0 :(得分:0)

只需在代码中添加以下内容:

    // this intent wraps voice recognition intent 
    PendingIntent pendingIntVoice = PendingIntent.getActivity(context, 0, intent, 0);
    pendingIntVoice.send();

换句话说,pendingIntent.send ();你没有调用语音识别器意图,但是当语音识别结束时应该自动调用的意图(事实上你用putExtra (RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, pendingIntent)行设置它)

答案 1 :(得分:0)

我想要类似的东西,这就是我提出的并且它有效。这是在服务中:

//IntentHandlerService extends IntentService
//The intent I want sent back to me after voice recognition is complete...
Intent inputTextIntent = new Intent(this, IntentHandlerService.class);
//...gets wrapped in this PendingIntent...
PendingIntent pendingIntent = PendingIntent.getService(this, 0, inputTextIntent, PendingIntent.FLAG_ONE_SHOT);
//...and added to the intent aimed for the recognizer...
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, pendingIntent);
//...which is the one you start.
startActivity(intent);