Board logo

標題: Android App - 計時器 [打印本頁]

作者: admin    時間: 2013-8-24 17:09     標題: Android App - 計時器

以下例子TextView1 會顯示數字, 由0 開始每秒加一
  1.    Timer t = new Timer();
  2.     int time=0;

  3.     @Override
  4.     public void onCreate(Bundle savedInstanceState) {
  5.         super.onCreate(savedInstanceState);
  6.         setContentView(R.layout.main);
  7.         mContext = this;
  8.   t.scheduleAtFixedRate(new TimerTask() {
  9.   @Override
  10.   public void run() {
  11.   runOnUiThread(new Runnable() {
  12.      public void run() {
  13.             TextView tv = (TextView) findViewById(R.id.textView1);
  14.             tv.setText(String.valueOf(time));
  15.             time += 1;
  16.         }         
  17.     });
  18.         //Called each time when 1000 milliseconds (1 second) (the period parameter)
  19.     }        
  20. },
  21. //Set how long before to start calling the TimerTask (in milliseconds)
  22. 0,
  23. //Set the amount of time between each execution (in milliseconds)
  24. 1000);
  25. }
複製代碼

作者: admin    時間: 2013-8-24 17:38

或者把上面程式以 method 處理

  1. Timer t = new Timer();
  2.    int time=0;

  3.     @Override
  4.     public void onCreate(Bundle savedInstanceState) {
  5.         super.onCreate(savedInstanceState);
  6.         setContentView(R.layout.main);
  7.         mContext = this;
  8.           t.scheduleAtFixedRate(new TimerTask() {

  9. @Override
  10. public void run() {              TimerMethod();
  11.          }        
  12.       },                    //Set how long before to start calling the TimerTask (in milliseconds)
  13.       0,                //Set the amount of time between each execution (in milliseconds)
  14.      1000);
  15. }

  16. private void TimerMethod()
  17. {
  18. //This method is called directly by the timer
  19. //and runs in the same thread as the timer.
  20. //We call the method that will work with the UI
  21. //through the runOnUiThread method.

  22. this.runOnUiThread(Timer_Tick);
  23. }

  24. private Runnable Timer_Tick = new Runnable() {
  25. public void run() {
  26. //This method runs in the same thread as the UI.   
  27.      TextView tv = (TextView) findViewById(R.id.textView2);
  28.     tv.setText(String.valueOf(time));
  29.     time += 1;
  30.    }
  31. };
複製代碼

作者: admin    時間: 2013-9-9 20:50

採用Timer 其中一個問題是不能隨時 enable 及disable timer, 我們可以採用 handle 做計時器




歡迎光臨 How2Do (http://forum.how2do.com.hk/) Powered by Discuz! 7.2