我在android中有一个计时器来倒计时未来的日期,但它并不令人耳目一新。任何帮助赞赏。我的代码发布在下面:
public class Activity1 extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView t = (TextView)findViewById(R.id.countdown);
t.setText(timeDif());
我相信t.setText只需要不断更新,但我不确定如何做到这一点。
}
public String timeDif()
{
GregorianCalendar then = new GregorianCalendar(2012, 07, 21, 6, 0, 0);
Calendar now = Calendar.getInstance();
long arriveMilli = then.getTimeInMillis();
long nowMilli = now.getTimeInMillis();
long diff = arriveMilli - nowMilli;
int seconds = (int) (diff / 1000);
int minutes = seconds / 60;
seconds %= 60;
int hours = minutes / 60;
minutes %= 60;
int days = hours / 24;
hours %= 24;
String time = days + ":" +zero(hours)+":"+zero(minutes)+":"+zero(seconds);
return time;
}
private int zero(int hours) {
// TODO Auto-generated method stub
return 0;
}
}
答案 0 :(得分:1)
除非您在自己的线程中执行此操作,否则文本框不会更新。 Timer运行在与UI不同的线程上。我就是这样做的。
myTimer = new Timer();
myTimerTask = new TimerTask() {
@Override
public void run() {
TimerMethod();
}
};
myTimer.schedule(myTimerTask, 0, 100);
private void TimerMethod()
{
//This method is called directly by the timer
//and runs in the same thread as the timer.
//We call the method that will work with the UI
//through the runOnUiThread method.
if (isPaused != true) {
this.tmrMilliSeconds--;
this.runOnUiThread(Timer_Tick);
}
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
//This method runs in the same thread as the UI.
if (tmrSeconds > 0) {
if (tmrMilliSeconds <= 0) {
tmrSeconds--;
tmrMilliSeconds = 9;
}
} else {
Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(1000);
myTimer.cancel();
tmrSeconds = setTime;
tmrMilliSeconds = 0;
isPaused = true;
}
//Do something to the UI thread here
timerText.setText(String.format("%03d.%d", tmrSeconds, tmrMilliSeconds));
}
};
这是我为ap制作的倒计时时钟代码的一部分。它演示了如何运行一个线程(public void run())部分,然后运行在UI线程上运行的另一个部分。希望有所帮助。
答案 1 :(得分:1)
你不应该用计时器这样做。计时器使用一个线程而你不需要一个(它会使事情变得不必要)。您需要使用Runable和Handler的postDelayed方法来执行此操作。它更轻松,重量更轻。
Handler mHandler = new Handler();
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
//update here
mHandler.postDelayed(mUpdateTimeTask, 100);
}
};
private void startTimer()
{
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
}
这是一个很棒的example。