Possible to open “Speak Now” dialog programmatically?

心已入冬 提交于 2019-12-22 18:48:12

问题


Is it possible to open the "Speak Now" dialog programmatically?

Currently, if the user taps my 'Search' button, a dialog opens and I have the soft keyboard open automatically so the user doesn't need to tap the textedit field.

I'd like to offer an alternate 'Search by voice' that will open the dialog and have the "Speak now" window open automatically. So the user doesn't have to find and tap the 'mic' button on the keyboard.

Any ideas?


回答1:


Yes, it is possible. Take a look at ApiDemos sample in the Android SDK. There is an activity named VoiceRecognition, it utilizes RecognizerIntent.

Basically, all you need to do is to craete a proper intent with some extras and then read the results.

private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;

private void startVoiceRecognitionActivity() {
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    // identifying your application to the Google service
    intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());
    // hint in the dialog
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
    // hint to the recognizer about what the user is going to say
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                    RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    // number of results
    intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
    // recognition language
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,"en-US");
    startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
        ArrayList<String> matches = data.getStringArrayListExtra(
                    RecognizerIntent.EXTRA_RESULTS);
        // do whatever you want with the results
    }
    super.onActivityResult(requestCode, resultCode, data);
}


来源:https://stackoverflow.com/questions/12876751/possible-to-open-speak-now-dialog-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!