Hello, nice to meet you again.
Today, I will develop a simple count down timer application. This is only a simple application which show you how to create a function to let time count down. You can use it in your larger application like Alarm Alert, …
Now, let’s do it.
First, create new Android project. I always use Android 2.3.3 for Minium Required SDK, lasted Android version (now is 4.3) in Target SDK and Android 2.3.3 for Compile With. OK, Next and Next. I finish creating new project.
Jump Ahead To:
IN MAIN_ACTIVITY.XML
Create a TextView
1
2
3
4
5
6
|
<TextView
android:id=“@+id/txtCountdown”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“Hello”
/>
|
OK, we switch to MainActivity.java file
IN MAINACTIVITY.JAVA FILE
Create a CountDownTimer object.
1
|
CountDownTimer count_obj;
|
Create a TextView object.
1
|
TextView tv_count;
|
In onCreate, write a code to create a new CountDownTimer which has 2 parameters
First Parameter: the total time (ex: 2 minutes 30 seconds, we change to milliseconds: 150000).
Second Parameter: the time which the action will repeat.
onTick: will be called after a time.
onFinish: will called after the total time finishes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
new CountDownTimer (150000, 1000){
@Override
public void onFinish() {
// TODO Auto-generated method stub
tv_count.setText(“Finish! Congratulation”);
}
@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
tv_count.setText(“” + formatTime(millisUntilFinished));
}
}.start();
|
We also have to write a function called format Time which has parameter millis.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public String formatTime(long millis)
{
String output = “00:00”;
long seconds = millis / 1000;
long minutes = seconds / 60;
seconds = seconds % 60;
minutes = minutes % 60;
String sec = String.valueOf(seconds);
String min = String.valueOf(minutes);
if(seconds < 10)
sec = “0” + seconds;
if(minutes < 10)
min = “0” + minutes;
output = min + ” : “ + sec;
return output;
}
|
OK, it is ok. I will test it to know that if it works well or not.
Yeah, it works well. Hope you can do that.