Following Wakim's suggestion the code would be this:
public class TesteActivity extends Activity {
Timer timer;
TimerTask timerTask;
final Handler handler = new Handler();
CheckBox checkBox1;
TextView textView1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.teste);
textView1 = (TextView)findViewById(R.id.textView1);
checkBox1 = (CheckBox)findViewById(R.id.checkBox1);
checkBox1.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
if(((CheckBox) v).isChecked()){//Se está checado inicializa o TimerTask
startTimer();
}
else{//se não pára o TimerTask
stopTimerTask();
}
}
});
}
public void startTimer() {
timer = new Timer();
//Inicializa o TimerTask
initializeTimerTask();
//Executa imediatamente o TimerTask, repetindo-o a cada 1s
timer.schedule(timerTask, 0, 1000); //
}
int i = 0;
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
//Coloque aqui o código que quer que seja executado quando
//o CheckBox está checked
//Neste exemplo o valor do textView será incementado em 1 a cada segundo
i++;
textView1.setText(Integer.toString(i));
}
});
}
};
}
public void stopTimerTask() {
//Pára o timer
if (timer != null) {
timer.cancel();
timer = null;
}
}
}
When CheckBox
is checked, TimerTask
is started. When the ckeck is removed the TimerTask
is stopped.
If TimerTask
does not need to be running when Activity is in the background, override the onPause
and onResume
methods like this:
@Override
protected void onPause() {
super.onPause();
stopTimerTask();
}
@Override
protected void onResume() {
super.onResume();
if(checkBox1.isChecked()){
startTimer();
}
}