我希望有一个计时器来计算用户完成任务所需的时间。从stackoverflow的其他问题我已经设计了以下方法(参见下面的代码)。我的问题 - >有更有效的方法吗?这看起来有点麻烦。
private Timer myTimer;
private SharedPreferences prefs;
private String prefName = "MyPref";
private static final String TIMER_KEY = "timer";
private static final String FINAL_TIMER_KEY = "final timer";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.crossword1);
//Start the timer ticking
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
TimerMethod();
}
}, 0, 1000);
}
private void TimerMethod()
{
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
//here i plan on using a shared preference to keep track of the time
//so each "Timer_Tick" would get the latest "TIMER_KEY", add a second to it
//and then re-store it in the shared preferences
}
};
答案 0 :(得分:1)
通过使用以下代码,您可以将时间打印为文本视图以及背景。
private Long startTime;
private Handler handler = new Handler();
startTime = System.currentTimeMillis();
handler.removeCallbacks(updateTimer);
handler.postDelayed(updateTimer, 1000);
private Runnable updateTimer = new Runnable() {
public void run() {
final TextView time = (TextView) findViewById(R.id.timer);
Long spentTime = System.currentTimeMillis() - startTime;
//計算目前已過分鐘數
Long minius = (spentTime/1000)/60;
//計算目前已過秒數
Long seconds = (spentTime/1000) % 60;
time.setText(minius+":"+seconds);
handler.postDelayed(this, 1000);
}
};