Android timer stuff

Wow, it’s been a while since I’ve last posted!

Just wanted to toss up some code for creating a timer in android. One would think you would just utilize the java.utils.Timer class but that creates a new thread and can create issues with your application. Plus it’s a pain to access stuff from the timer. Android has an alternative to keep everything all together and it’s quite easy to implement.

private Handler timerHandler;
private int timerTime = 5000; //in milliseconds
private void createTimer()
{
	timerHandler = new Handler();

}
private void startTimer()
{
	//resets timer and posts the delayed call
	rotationHandler.removeCallbacks(mUpdateTimeTask);
	rotationHandler.postDelayed(mUpdateTimeTask, timerTime);
}
private void stopTimer()
{
	rotationHandler.removeCallbacks(mUpdateTimeTask);
}
private Runnable mUpdateTimeTask = new Runnable()
{
	   public void run() {
	       //do your thing

		//repeat timer if you need to
		rotationHandler.postDelayed(this, timerTime);
		
	   }
};

Posted

in

, ,

by

Tags:

Comments

Leave a Reply