2011-08-09 4 views
1

질문이 있습니다. 이 코드 타이머가 정확합니까;]? 또는 나는 그것을 더 쉽게android timer problem

package timer2.android; 

import java.util.Timer; 
import java.util.TimerTask; 

import android.app.Activity; 
import android.os.Bundle; 
import android.widget.TextView; 

public class Timer2Activity extends Activity { 

private TextView tv; 
private Timer myTimer; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    tv = (TextView)findViewById(R.id.textView1); 

    myTimer = new Timer(); 
    myTimer.schedule(new TimerTask() { 
     @Override 
     public void run() { 
      TimerMethod(); 
     } 

    }, 0, 1000); 
} 

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. 
    this.runOnUiThread(Timer_Tick); 
} 

long mStartTime = System.currentTimeMillis(); 

private Runnable Timer_Tick = new Runnable() { 
    public void run() { 
     final long start = mStartTime; 
     long millis = System.currentTimeMillis() - start; 
     int seconds = (int) (millis/1000); 
     int minutes = (int) (seconds/60); 
     seconds  = seconds % 60; 

     if (seconds < 10) 
     { 
      tv.setText("" + minutes + ":0" + seconds); 
     } 
     else 
     { 
      tv.setText("" + minutes + ":" + seconds);    
     } 

     //a++; 

    //This method runs in the same thread as the UI.    

    //Do something to the UI thread here 

    } 
}; 

}

+0

이것은 실제로 트릭을 할 것입니다. 물론 다른 여러 가지 방법이 있지만 모두 똑같이 할 것입니다. – nhaarman

답변

0

여기 아무 잘못 볼 수 없습니다 할 수 있습니다. 그러나 추가 스레드를 생성하지 않으므로 타이머에는 Handler을 사용해야합니다. 여기에 예제를 참조하십시오 : Repeat a task with a time delay?

+0

도움에 감사드립니다. :)) – Peter