我有一个活动,它不断向用户朗读单词,并在代码完成时结合使用onUtteranceCompleted和textTospeech来显示内容。
在onUtteranceCompleted中,我有一段代码,用来延迟函数的执行时间:
Runnable task = new Runnable() {
public void run() {
//runs on ui
runOnUiThread(new Runnable() {
public void run() {
readWord();
}
});
}
};
worker.schedule(task, 1, TimeUnit.SECONDS);这看起来工作得很好,但我认为它造成了一个问题。当我旋转手机屏幕时(我猜这会启动一个新的活动)。我听到背景中有人在读一些单词。我猜这是因为runOnUiThread()使活动在后台继续。
我怎样才能避免2个活动运行?如果我不需要在做一些奇怪的补丁时停止屏幕旋转,我会更喜欢!
谢谢
编辑:
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:
worker的实例化:
private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();发布于 2012-02-26 08:13:07
好的,这是我想出的一个解决方案,如果有人有更好的解决方案,我会倾听。
我已经在androidmanifest中的活动中添加了
然后是一个在屏幕旋转时调用的函数:
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
setContentView(R.layout.streaming);
initializeUI(); //contains all the findViewByID etc...
}发布于 2012-02-29 01:32:24
我会使用处理程序而不是runOnUiThread()。
首先,您正在使用一个启动另一个线程的线程-为什么?
其次,如果您创建了一个简单的处理程序,它应该会在旋转配置更改时杀死自己。即:
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// do your background or UI stuff
}
};然后使用Thread调用处理程序,它将启动您想要在UI线程上运行的任何进程:
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();https://stackoverflow.com/questions/9448342
复制相似问题