0

我在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;
}


} 
4

2 回答 2

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 制作的倒计时时钟代码的一部分。它演示了如何让一个线程运行(公共 void run())部分,然后在 UI 线程上运行另一部分。希望有帮助。

于 2011-11-28T01:24:17.180 回答
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);
    }
于 2011-11-28T01:38:31.077 回答