我正在使用Android语音识别意图,但我想知道用户设置用于识别的语言。 RecognizerIntent上的文档暗示你可以从意图数据中得到这个,但我一直都是空的。
调用Intent时这些值是否可用?有没有其他方法来获取这些数据?
以下是我如何调用意图:
private void startVoiceRecognitionActivity() {
Logger.i(AppConfig.LOGTAG, "startVoiceRecognitionActivity");
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "speech recognition demo");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
我得到的结果如下:
/**
* Handle the results from the recognition activity.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
Logger.i(AppConfig.LOGTAG, "EXTRA_LANGUAGE = "+data.getStringExtra(RecognizerIntent.EXTRA_LANGUAGE));
Logger.i(AppConfig.LOGTAG, "EXTRA_LANGUAGE_MODEL = "+data.getStringExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL));
Logger.i(AppConfig.LOGTAG, "EXTRA_LANGUAGE_PREFERENCE = "+data.getStringExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE));
} else {
Toast.makeText(getApplicationContext(), "Voice recognition failed.", Toast.LENGTH_LONG).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
答案 0 :(得分:1)
您似乎需要发送广播来询问语音识别中配置的语言。所以,顺序是
以下代码:
/**
* Handle the results from the recognition activity. First thing to do is
* to get the language...
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
Intent intent = new Intent(RecognizerIntent.ACTION_GET_LANGUAGE_DETAILS);
LangBroadcastReceiver myBroadcastReceiver = new LangBroadcastReceiver(this, data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS));
sendOrderedBroadcast(intent, null, myBroadcastReceiver, null, Activity.RESULT_OK, null, null);
} else {
Toast.makeText(getApplicationContext(), "Voice recognition failed.", Toast.LENGTH_LONG).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* After a voice recognition is performed, need to sent a broadcast to
* request the language used. This BroadcastReceiver gets the response and
* then processes the original recognisedText from the
* ACTION_RECOGNIZE_SPEECH Intent.
*
*/
public class LangBroadcastReceiver extends BroadcastReceiver {
ArrayList<String> recognisedText;
Activity parentActivity;
/**
* Store these for later use...
* @param activity
* @param arrayList
*/
LangBroadcastReceiver(Activity activity, ArrayList<String> arrayList) {
recognisedText = arrayList;
parentActivity = activity;
}
@Override
public void onReceive(Context context, Intent intent) {
Bundle results = getResultExtras(true);
String lang = results.getString(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE);
Log.d(AppConfig.LOGTAG, "MyBroadcastReceiver: Got 'EXTRA_LANGUAGE_PREFERENCE' = " + lang);
// now handle the recognisedText with the known language.
}
}