我有疑问。这个代码计时器是否正确;]?或者我可以更容易地做到这一点
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 :(得分:0)
这里看不出任何错误。但是你应该使用Handler
作为计时器,因为它不会创建额外的线程。请参阅此处的示例:Repeat a task with a time delay?