emb*_*ire 18 android timer onresume timertask onpause
我的Android应用程序中有一个动画,它会闪烁TextView不同的颜色.我使用了TimerTask,Timer和Runnable方法来实现它.我需要做的是在用户在onPause()期间离开应用程序时停止线程,并在用户返回onResume()中的应用程序时恢复线程.以下是我实现的代码,但它不起作用(onPause()和onResume()件),我不明白为什么.我已经阅读了其他类似问题的其他帖子,但他们没有帮我弄清楚在我的情况下该怎么做.我已经读过TimerTasks已经过时了,我应该使用ExecutorService方法; 我不清楚如何实现这个功能.
...timerStep5 = new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (b5) {
cashButton2SignalText.setBackgroundColor(Color.RED);
cashButton2SignalText.setTextColor(Color.WHITE);
b5=false;
} else {
cashButton2SignalText.setBackgroundColor(Color.WHITE);
cashButton2SignalText.setTextColor(Color.RED);
b5=true;
}
}
});
}
};
timer5.schedule(timerStep5,250,250);
}
public void onPause(){
super.onPause();
timerStep5.cancel();
}
public void onResume(){
super.onResume();
timerStep5.run();
}
Run Code Online (Sandbox Code Playgroud)
Xia*_*ang 13
一个经过TimerTask
被取消,不能再运行,你必须创建一个新的实例.
阅读详情:
ScheduledThreadPoolExecutor
建议用于较新的代码,它处理异常和任务的情况比预定的时间间隔花费更长的时间.
但对于你的任务,TimerTask
应该足够了.
我是这样做的。在发生暂停的地方添加pauseTimer
布尔值(也许是按钮侦听器),如果为 true,则不计算计时器。
private void timer (){
Timer timer = new Timer();
tv_timer = (TextView) findViewById(R.id.tv_locationTimer);
countTimer = 0;
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
String s_time = String.format("%02d:%02d:%02d",
countTimer / 3600,
(countTimer % 3600) / 60,
countTimer % 60);
tv_timer.setText(s_time);
if (!pauseTimer) countTimer++;
}
});
}
}, 1000, 1000);
}
Run Code Online (Sandbox Code Playgroud)