Skip to content

Instantly share code, notes, and snippets.

@pokk
Last active April 5, 2017 02:42
Show Gist options
  • Save pokk/462aae65493ca7ae07980b1c13db2945 to your computer and use it in GitHub Desktop.
Save pokk/462aae65493ca7ae07980b1c13db2945 to your computer and use it in GitHub Desktop.
A great variety of timer in Android
private static final int COUNTDOWN_TIME = 3 * 1000;
private static final int COUNTDOWN_INTERVAL = 1 * 1000;
public CountDownTimer countDownTimer = null;
countDownTimer = new CountDownTimer(COUNTDOWN_TIME, COUNTDOWN_INTERVAL)
{
@Override
public void onTick(long millisUntilFinished)
{
// Each of second.
}
@Override
public void onFinish()
{
// This timer is time over.
// **Implement your action.
}
};
countDownTimer.start();
countDownTimer.cancel();
private Handler handler = new Handler();
private Runnable runnable = new Runnable()
{
public void run()
{
// **Implement your action.
handler.postDelayed(this, 1000);
// postDelayed(this, 1000) means put a Runnable object in the main thread.
}
};
handler.postDelayed(runnable, 1000); // Start the timer.
handler.removeCallbacks(runnable); // Stop the timer
Timer timer = new Timer();
TimerTask task = new TimerTask()
{
public void run ()
{
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
};
final Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
switch (msg.what)
{
case 1:
// **Implement your action.
break;
}
super.handleMessage(msg);
}
};
protected void onDestroy ()
{
if (timer != null)
{
timer.cancel();
timer = null;
}
super.onDestroy();
}
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
// timer.schedule(task, 5000) means just execute once time only.
// timer.schedule(task, 1000, 5000) means starting this timer and repeat in a sec.
timer.schedule(task, 1000, 5000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment