我尝试为 android 应用程序编写一个代码,该代码采用从谷歌语音 api 返回的字符串,并使用它在同一线程内发送到其他对象“levenshte.testLevenshteindistance”。
我不能让它同步工作的问题!我的意思是我的代码在谷歌语音 api 返回值“取决于互联网速度”之前调用对象?!
ublic class MainActivity extends Activity {
public ListView sList;
ArrayList<String> names;
int sfound;
mp3Player mp3Player;
Levenshteindistance levenshte;
public static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
voiceinputbuttons();
starVoiceRecognation();
}
private void starVoiceRecognation() {
Thread timer = new Thread(){
public void run(){
new VoiceRecognizer().execute();
//names is an ArrayList returnd by google speech api
sfound=levenshte.testLevenshteindistance(names.get(0).toString());
}
};timer.start();
}
public void voiceinputbuttons() {
sList = (ListView) findViewById(R.id.list);
//default value if create mp3player before set sName or rName or actionNumbe
names=null;
levenshte = new Levenshteindistance();
}
public void informationMenu() {
startActivity(new Intent("android.intent.action.INFOSCREEN"));
}
public void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,"Speech recognition demo");
try {
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
} catch (ActivityNotFoundException e) {
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
// i want the timer thread wait until assign a value to this name variable
names = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (names.contains("information")) {
informationMenu();
}
super.onActivityResult(requestCode, resultCode, data);
}
}
private class VoiceRecognizer extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... url1) {
startVoiceRecognitionActivity();
return null;
}
}
}
我想确保在调用 levenshte.testLevenshteindistance(names.get(0).toString()); 时名称不为空