Saturday, October 8, 2011

CountDownTimer a great alternate of AlarmManager in Android

Hi Guys,
few days back I was looking for a solution to execute a functionality after some time from my activity. Generally in these cases developer uses AlarmManager to send Action or Activity and handle it in their accordingly. But there are few limitations with AlarmManager like you have to set your alarm for a fix time from boot-up or start. So to overcome this I used CountDownTimer class. This is the same class which is used in StopWatch application, so it is reliable as well as easy to use. Although it’s use is pretty straight forward and mentioned in the API. I will explain it here with the same example.
Example :
new CountdownTimer(30000, 1000) {

 public void onTick(long millisUntilFinished) {

 mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);

}

 public void onFinish() {

  mTextField.setText("done!");

}

 }.start();
Here 30,000(30 sec) is the timer till it will go, 1000(1 sec) is every step to reach there. Here there are two  methods which needs to be override, first is onTick() which will be called on every step. So it means it will be called on every second in this case till 29 sec. After that onFinish() method will be called and execution control will come out of it.
So suppose if you want to start some activity after 30 sec. just put that intent and sendBroadcast() in th onFinish() method.
Hope this will help you.

No comments: