Reputation: 643
I have written a program for a countdown timer but the countdown starts only on button click , but i want it to start without the button click , can anyone suggest me how to do it without the button click ?
Here is the code for countdown timer
public class MainActivity extends ActionBarActivity {
CountDownTimer countDownTimer;
boolean timehasstarted = false;
Button btnStart;
TextView timer;
long startTime = 30 * 1000;
long interval = 1 * 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.button1);
timer = (TextView) findViewById(R.id.timer);
timer.setText(timer.getText() + String.valueOf(startTime / 1000));
btnStart.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!timehasstarted) {
countDownTimer.start();
timehasstarted = true;
timer.setText("Stop");
} else {
countDownTimer.cancel();
timehasstarted = false;
timer.setText("Restart");
}
}
});
countDownTimer = new CountDownTimer(startTime, interval) {
@Override
public void onTick(long millisUntilFinished) {
timer.setText("" + millisUntilFinished / 1000);
}
@Override
public void onFinish() {
timer.setText("Time's Up!");
}
};
}
Upvotes: 2
Views: 1630
Reputation: 12378
Move your timer code to onCreate()
method of the Activity instead of the onClick()
method
This will start the timer on activity start.
And also you can use timer.cancel()
to cancel the timer when the activity is stopped or not currently active
Upvotes: 1
Reputation: 26
if you want to turn on the countdown after a particular time say after 2 sec then you can use TimerTask for this for exmaple :
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
}
}, 2000);
Upvotes: 0