0

I've got an activity that keeps reading words to the user, and using onUtteranceCompleted with textTospeech to display something when the code is completed.

Inside onUtteranceCompleted I have this code to delay a function with a second:

Runnable task = new Runnable() {
    public void run() {
        //runs on ui
        runOnUiThread(new Runnable() {
            public void run() {
                readWord();
            }
        });
    }
};
worker.schedule(task, 1, TimeUnit.SECONDS);

This seems like it works well, but I think it is causing a problem. When I rotate the screen of my phone (I guess this starts a new activity). I hear some words being read in the background. I guess this is because of runOnUiThread() which makes the activity continue in the background.

How could I avoid 2 activities running ? I would prefer if I don't have to stop the screen from rotating on doing some weird patch!

Thank you

EDIT:

public void readWord() {
    if (this.readingOnPause) {
        return;
    }

    txtCurrentWord.setText(currentItem[1]);

    this.hashAudio.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"word");
    this.tts.setLanguage(Locale.US);
    this.tts.speak(this.currentItem[1], TextToSpeech.QUEUE_FLUSH,this.hashAudio);
}

EDIT2:

instantiation of worker:

private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
Andrei
  • 1,183
  • 2
  • 19
  • 40

2 Answers2

2

I would use a Handler instead of runOnUiThread().

For one thing, you're using a Thread that starts another Thread - why?

Secondly, if you create a simple Handler, it should kill itself on the rotate config change. IE:

private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        // do your background or UI stuff
    }
};

Then later use a Thread to call the handler, which will kick off whatever process you want to run on the UI thread:

new Thread() {
    @Override
    public void run() {
        long timestamp = System.currentTimeMillis();
        // thread blocks for your 1 second delay
        while (System.currentTimeMillis() - timestamp <= 1000) {
            // loop
        }

        handler.sendEmptyMessage(0);
    }
}.start();
Shinzul
  • 286
  • 2
  • 11
0

Ok so this is a fix I've come up with, if someone has a better solution, I'm listening.

  1. I've added android:configChanges="keyboardHidden|orientation" inside the activity in the androidmanifest
  2. 2.

and then a function that is called when the screen is rotate:

@Override
public void onConfigurationChanged(Configuration newConfig)
{
  super.onConfigurationChanged(newConfig);
  setContentView(R.layout.streaming);

  initializeUI(); //contains all the findViewByID etc...
}
Andrei
  • 1,183
  • 2
  • 19
  • 40