首页 > 解决方案 > 语音识别无法从片段中工作

问题描述

我有一个使用 ACTION_RECOGNIZE_SPEECH 意图的应用程序。当我从 Activity 调用 startActivityForResult 并且相应的 onActivityResult 在同一个 Activity 中时,它工作正常。

我的问题是我有另一个使用片段的应用程序。如果我从 Fragment 调用 startActivityForResult,则不会出现语音框。

我试过的:

我尝试在父 Activity 中覆盖 onActivityResult,然后调用 getActivity.startActivityForResult(intent, SPEECH_REQUEST_CODE); 这只是启动意图并执行 Activity 类中的 onActivityForResult。

我已经尝试了以下帖子中的各种组合。

片段中未调用 onActivityResult

这是我目前拥有的代码和日志。有人有什么建议吗?

注意我在清单中也有以下权限:

<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.INTERNET" />

.

家长活动:

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.e(TAG, "inside onActivityForResult in parent. requestCode = " + requestCode + "resultCode = " + requestCode + " data = " + data );
    }

.

片段类:

private static final int SPEECH_REQUEST_CODE = 0;

    // Create an intent that can start the Speech Recognizer activity
    private void displaySpeechRecognizer() {
        Log.e(TAG, "inside displaySpeechRecognizer() and speechRequestCode = " + SPEECH_REQUEST_CODE);
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
// Start the activity, the intent will be populated with the speech text
        startActivityForResult(intent, SPEECH_REQUEST_CODE);
    }

    // This callback is invoked when the Speech Recognizer returns.
// This is where you process the intent and extract the speech text from the intent.
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        Log.e(TAG, "inside onActivityForResult in child fragment. requestCode = " + requestCode + " resultCode = " + resultCode);

        if (requestCode == SPEECH_REQUEST_CODE && resultCode == RESULT_OK) {
            List<String> results = data.getStringArrayListExtra(
                    RecognizerIntent.EXTRA_RESULTS);
            String spokenText = results.get(0);
            // Do something with spokenText
            Log.e(TAG, "spokenText = " + spokenText);
            etCommentEditText.append(" " + spokenText);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

.

日志:

    05-02 14:57:37.012 14414-14414/com.carefreegroup.rr3.carefreeoncall E/AlertDetailsFragment: inside displaySpeechRecognizer() and speechRequestCode = 0
05-02 14:57:37.072 14414-14414/com.carefreegroup.rr3.carefreeoncall E/AlertDetailsFragment: inside onActivityForResult in child fragment. requestCode = 0 resultCode = 0

标签: androidandroid-fragmentsspeech-recognition

解决方案


你必须打电话recognizer.startListening(speechIntent);和停止recognizer.stopListening();

现在它在片段中工作。

假设,您想在单击按钮调用上述方法时初始化语音识别器。


推荐阅读