所有你需要知道的:我有一个带有按钮的对话框.按下按钮时,我想在MainActivity中启动语音识别.(该对话框由另一个类创建,我通过界面处理点击).
所以这是相关的代码:(在MainActivity中)
public void speechToText(boolean isName) {
this.isName = isName;
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault().toString());
//intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.prompt));
try {
startActivityForResult(intent, RESULT_SPEECH);
Toast.makeText(getApplicationContext(),
"started acitvity for result", //test toast
Toast.LENGTH_SHORT).show();
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_to_text_not_supported),
Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if(isName)
currentName = text.get(0);
else …Run Code Online (Sandbox Code Playgroud)