如何使用来自其他线程 "CalledFromWrongThreadException" 的 activity

How to use activity from some another thread "CalledFromWrongThreadException"

我使用 MediaPlayer TextToSpeech 类。我需要抓住演讲结束的时刻。我使用此代码:

    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp)
        {
            speechRecognizer.startListenig();
            //binding.play.performClick();
        }
    });

    TTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
        @Override
        public void onDone(String utteranceId) {
            speechRecognizer.startListenig();
        }
        @Override
        public void onError(String utteranceId) { }
        @Override
        public void onStart(String utteranceId) { }
    });

两个监听器都启动这个方法:

public void startListenig(){
    binding.progressSound.setVisibility(View.VISIBLE);
    binding.progressSound.setIndeterminate(true);
    speech.startListening(recognizerIntent);

}

Media Player 的监听器工作正常。 Text To Speech 的监听器抛出异常:

 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

我试过 google 这个,但我不明白问题的根源,为什么在使用媒体播放器的情况下它可以工作,为什么 TTS 会抛出异常。

请告诉我如何解决这个问题。

当你对视图进行任何操作时,必须是主线程,如果你在其他线程中则不能在该线程中执行操作。

使用

runOnUiThread(new Runnable() {
        @Override
        public void run() {

        }
    });

activity 的方法,片段或适配器使用 context.runOnUiThread()

如果 runOnUiThread() 无法使用,

new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
          // This is your code  
        } 
    });