How can I Toast after Text to Speech finish speaking Android

前端 未结 2 666
北恋
北恋 2021-01-20 16:59

How can I Toast after Text to Speech finish speak. Actually I want to do someting more than Log. This is my code.

public class MainActivity extends AppCompat         


        
相关标签:
2条回答
  • 2021-01-20 17:06

    onUtteranceCompleted is deprecated. use OnUtteranceProgressListener

    Code Snippet

    textToSpeech=new TextToSpeech(this, new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status==TextToSpeech.SUCCESS){
                int result=textToSpeech.setLanguage(Locale.ENGLISH);
    
                if (result==TextToSpeech.LANG_MISSING_DATA||result==TextToSpeech.LANG_NOT_SUPPORTED){
                    Log.i("TextToSpeech","Language Not Supported");
                }
    
                textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
                    @Override
                    public void onStart(String utteranceId) {
                        Log.i("TextToSpeech","On Start");
                    }
    
                    @Override
                    public void onDone(String utteranceId) {
                        Log.i("TextToSpeech","On Done");
                    }
    
                    @Override
                    public void onError(String utteranceId) {
                        Log.i("TextToSpeech","On Error");
                    }
                });
    
            }else {
                Log.i("TextToSpeech","Initialization Failed");
            }
        }
    });
    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,null,TextToSpeech.ACTION_TTS_QUEUE_PROCESSING_COMPLETED);
    }
    
    0 讨论(0)
  • 2021-01-20 17:17

    You try to show a Toast in a thread that is not the UI(main) thread. You should change this

    @Override
    public void onUtteranceCompleted(String utteranceId) {
        Log.i("CALLBACK", utteranceId); //utteranceId == "SOME MESSAGE"
        Toast.makeText(getApplicationContext(),"Call     Back",Toast.LENGTH_LONG).show();// I Cannot Toast here. Or do something more than Log
    }
    

    into this

    @Override
    public void onUtteranceCompleted(String utteranceId) {
        Log.i("CALLBACK", utteranceId); //utteranceId == "SOME MESSAGE"
    
        runOnUiThread(new Runnable() {
    
            public void run() {
                Toast.makeText(getApplicationContext(),"Call Back",Toast.LENGTH_LONG).show();
            }
        });
    }
    

    That way your code is dispatched to the main thread where you are allowed to show Toasts

    0 讨论(0)
提交回复
热议问题