Search code examples
javaandroidtimersharedpreferencesrunnable

Most efficient way to have a timer in an activity


I want to have a timer that counts the amount of time it takes for the user to complete a task. From other questions on stackoverflow I have devised the following approach (see code below). My question - > Is there a more efficient way of doing this? It seems a bit cumbersome.

    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

    }
};

Solution

  • By using following code, you can print the time as the text view and as well as background.

    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);
        }
    };