Created
August 4, 2017 18:24
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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