android - 语音识别无法从片段中工作
问题描述
我有一个使用 ACTION_RECOGNIZE_SPEECH 意图的应用程序。当我从 Activity 调用 startActivityForResult 并且相应的 onActivityResult 在同一个 Activity 中时,它工作正常。
我的问题是我有另一个使用片段的应用程序。如果我从 Fragment 调用 startActivityForResult,则不会出现语音框。
我试过的:
我尝试在父 Activity 中覆盖 onActivityResult,然后调用 getActivity.startActivityForResult(intent, SPEECH_REQUEST_CODE); 这只是启动意图并执行 Activity 类中的 onActivityForResult。
我已经尝试了以下帖子中的各种组合。
这是我目前拥有的代码和日志。有人有什么建议吗?
注意我在清单中也有以下权限:
<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
解决方案
你必须打电话recognizer.startListening(speechIntent);
和停止recognizer.stopListening();
现在它在片段中工作。
假设,您想在单击按钮调用上述方法时初始化语音识别器。
推荐阅读
- node.js - SyntaxError:标识符“__dirname”已被声明
- java - 在客户端和服务器之间发送数据作为字节数组
- symfony - 如何在 Symfony 中持久化 OneToMany 关系数据?
- ios - 使用身体 Alamofire 发布请求
- php - Symfony 5.1 选择列表过滤
- javascript - Cognito - adminRespondToAuthChallenge 返回用户的无效会话
- python - 如何避免每天多次抓取网站时下载重复文件(pdf)?
- java - 如何在 Spring 中从组件调用配置中的 SFTP 出站网关操作
- powershell - 在 Powershell 中以自定义格式将数据导出到 CSV 文件
- stripe-payments - Stripe 支付意图是在确认之前还是之后搁置?