我的 android 应用程序有语音识别问题。我的问题是我想显示与 jellybean 键盘显示的相同的语音识别输入屏幕。如果我从代码中调用语音识别意图,它不会继续收听并过早停止。必须有一个简单的方法来做到这一点,但我找不到它。
这是我的代码
package com.bsdcservices.recognitiontest;
import java.util.ArrayList;
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private final String TAG = "RecognitionTest";
private final int SPEECHRECOGNITION_RESULTCODE = 0;
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.textbox);
Button recognize = (Button) findViewById(R.id.recognize);
recognize.setOnClickListener(buttonClickListener);
}
public OnClickListener buttonClickListener = new OnClickListener(){
@Override
public void onClick(View v) {
startSpeechRecognitionActivity();
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
void startSpeechRecognitionActivity(){
// MyApplication.speechRecognitionActive = true;
// main.startSpeechRecognizer(TABSPEAK);
try{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault().toString());
startActivityForResult(intent, SPEECHRECOGNITION_RESULTCODE);
} catch (ActivityNotFoundException error) {
Toast.makeText(getBaseContext(), "Speech recognition is not supported by your device" , Toast.LENGTH_LONG).show();
} catch( RuntimeException error ) {
Toast.makeText(getBaseContext(), error.getMessage() , Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try
{
if (requestCode == SPEECHRECOGNITION_RESULTCODE) {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
editText.append(text.get(0));
}
}
} catch( RuntimeException error ) {
Toast.makeText(getBaseContext(), error.getMessage() , Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}
}