0

我想要一个计时器来计算用户完成任务所需的时间。从关于 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

    }
};
4

1 回答 1

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);
    }
};
于 2012-12-20T13:11:49.797 回答