I am working on android quiz and want timer on my each question-answer page. I have menu page in my quiz and play button to start game. And i want this timer is triggered wh
As mentioned by Piyush Gupta, you should call the setTimer()
method from onResume
in your QuestionActivity
.
From the Android Developer Documentation:
(onResume is) called for your activity to start interacting with the user. This is a good place to begin animations, open exclusive-access devices (such as the camera), etc.
In your code you should also make the counterTimer
you use in setTimer()
a class member, not a local variable; if you don't it will go out of scope once the setTimer()
call completes and your access to it will be lost.
So you will need to add the following to QuestionActivity
:
public class QuestionActivity extends Activity implements OnClickListener{
// NEW: add counterTimer as a member
private CountDownTimer counterTimer;
// NEW: implement onResume
@Override
public void onResume() {
setTimer();
super.onResume();
}
// CHANGE: setTimer should be changed as follows
public void setTimer() {
long finishTime = 5;
// NOTE: use the member, instead of a local
counterTimer = new CountDownTimer(finishTime * 1000, 1000) {
public void onFinish() {
//code to execute when time finished
}
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
if (seconds < 10) {
txtTimer.setText("" + minutes + ":0" + seconds);
} else {
txtTimer.setText("" + minutes + ":" + seconds);
}
}
};
counterTimer.start();
}
}
This above example uses your code as it is now, but I would advise you to create the timer in onCreate
using the class member to store it (ie. everything that is currently in setTimer(), except for the counterTimer.start();
call. Then just use counterTimer.start();
in onResume
. And maybe add a counterTimer.cancel()
call to onPause
so that the timer ends when the activity loses focus.