How to access layout in TTS OnUtteranceCompleted callback?

本小妞迷上赌 提交于 2019-12-22 17:52:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!