我在一个等待20秒的线程中有一个计时器,然后转移到一个新的活动,我正在寻找的是显示时间中textView中的任何减少或增加的时间。 这是我的代码:
Thread timer = new Thread() {
public void run() {
try {
sleep(ie);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent i = new Intent(Activity.this, Menu.class);
if (ie == 20000) {
startActivity(i);
overridePendingTransition(R.anim.pushin, R.anim.pushout);
}
}
}
};
timer.start();
感谢您的帮助
答案 0 :(得分:1)
尝试使用CountDownTimer而不是Thread:
CountDownTimer count = new CountDownTimer(20000, 1000)
{
int counter = 20;
@Override
public void onTick(long millisUntilFinished)
{
// TODO Auto-generated method stub
counter--;
textView.setText(String.valueOf(counter));
}
@Override
public void onFinish()
{
startActivity(i);
overridePendingTransition(R.anim.pushin, R.anim.pushout);
}
};
count.start();
答案 1 :(得分:0)
Camilo Sacanamboy的回答是正确的。如果你想用一个Thread做这个,一个解决方案可能是这样的:
final TextView status; //Get your textView here
Thread timer = new Thread() {
public void run() {
int time = 20000;
try {
while(time > 0){
time -= 200; //Or whatever you might like
final int currentTime = time;
getActivity().runOnUiThread(new Runnable() { //Don't update Views on the Main Thread
@Override
public void run() {
status.setText("Time remaining: " + currentTime / 1000 + " seconds");
}
});
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent i = new Intent(Activity.this, Menu.class);
if (ie == 20000) {
startActivity(i);
overridePendingTransition(R.anim.pushin, R.anim.pushout);
}
}
}
};
timer.start();