Skip to content

Instantly share code, notes, and snippets.

@Binary-Finery
Created August 4, 2017 18:24
Show Gist options
  • Save Binary-Finery/24bb2213be4e4b13fc629552ed6f0dc1 to your computer and use it in GitHub Desktop.
Save Binary-Finery/24bb2213be4e4b13fc629552ed6f0dc1 to your computer and use it in GitHub Desktop.
A simple working demonstration of using a Handler for the purposes of a count down timer
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView textView;
private Button btnStart;
private Handler countDownTimer;
private Runnable runnable;
private final int TIMER_DELAY = 1000;
private int duration = 20;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
textView = (TextView)findViewById(R.id.text_view);
btnStart = (Button)findViewById(R.id.button_start) ;
btnStart.setOnClickListener(this);
countDownTimer = new Handler();
runnable = new Runnable() {
@Override
public void run() {
if (duration > 0){
countDownTimer.postDelayed(this, TIMER_DELAY);
textView.setText(String.format(Locale.getDefault(), "%d seconds", duration));
duration--;
}else{
countDownTimer.removeCallbacks(runnable);
textView.setText("Time's up!");
letsDoSomething();
}
}
};
}
@Override
public void onClick(View v) {
if (v == btnStart){
countDownTimer.post(runnable);
}
}
private void letsDoSomething(){
/* to do on timer finish */
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment