1

我尝试为 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()); 时名称不为空

4

1 回答 1

2

你为此设置错误。您不会在任务中启动语音识别并假设它会在某个计时器运行时结束。语音识别需要时间,完成后它会在 onActivityResult 中回叫您。你应该在那里开始你的新活动。

此外,语音识别活动可能会在出错时返回 null。无论如何,我都会做一个空检查,只是为了确保。

于 2013-04-08T18:29:37.027 回答