我已经在MainActivity.java中设置了2分钟的计时器,如果我转到其他活动并返回MainActivity,计时器将被重置。但我希望计时器运行,即使活动被更改。请帮忙解决这个问题。 这是我的计时器代码。
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView tv = (TextView) findViewById(R.id.main_timer_text);
tv.setText(String.valueOf(minutes)+":"+String.valueOf(seconds));
seconds -= 1;
if(seconds == 0)
{
tv.setText(String.valueOf(minutes)+":"+String.valueOf(seconds));
seconds=60;
minutes=minutes-1;
}
}
});
}
}, 0, 1000);
}
答案 0 :(得分:0)
使用CountDownTimer
,因为onTick(long)
的呼叫已同步
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
text.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
text.setText("done!");
}
}.start();
来源:http://developer.android.com/reference/android/os/CountDownTimer.html
答案 1 :(得分:0)
试试这个示例代码......
final Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
int k = -1000;
@Override
public void run() {
if (k == 2 * 60 * 1000) {
timer.cancel();
timer.purge();
Log.i(TAG, "Timer cancelled");
return;
}
runOnUiThread(.... do your work....);
k += 1000;
Log.i(TAG, "Timer running...");
}
}, 0, 1000);
在onCreate()...
中写下这个