问题
I am making a simple Android program that runs mnemonics or math exercises for training purposes. I have a "new exercise" button that changes question and answer. I want to implement a "text to speech" mode, where the software reads the question and the answer. After they are spoken, it should calculate a new question and start again.
I am using OnUtteranceCompleted to determine if the speech has ended. My problem is that I can’t access my "new exercise" button from the callback.
I am using this:
private TextToSpeech.OnUtteranceCompletedListener onUtteranceCompleted = new TextToSpeech.OnUtteranceCompletedListener()
{
@Override
public void onUtteranceCompleted(String utteranceId)
{
if(0 == utteranceId.compareToIgnoreCase(END_OF_SPEECH))
{
Log.i("TTS","Completed");
if (TTSMode == TTS_MODE_ON) {
//Start new
Log.i("TTS","TTS mode is on: start new exercize");
NewExercize();
btnNewEx.performClick();
}
}
}
};
I got the following error: $CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
I am able to generate the new question/answer, but I can’t use the button to change the fields with the new question or answer, wich are used by the TTS engine.
Any ideas?
回答1:
You need to use runOnUiThread
:
context.runOnUiThread( new Runnable() {
public void run() {
btnNewEx.performClick();
}
});
(you can omit "context." if "this" is an Activity or Service subclass)
来源:https://stackoverflow.com/questions/12134766/how-to-access-layout-in-tts-onutterancecompleted-callback