Android - Cycle to check whether a CheckBox is enabled or not

1

Within the event of a Button I have a while loop that is constantly checking the status of a CheckBox . The problem is that if CheckBox is activated, Freeze! Can anyone help me with this?

botao.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        while(checkbox1.isSelected()){

            Toast.makeText(MainActivity.this, "CheckBox está ativada!", Toast.LENGTH_SHORT).show();

            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {e.printStackTrace();}
        }

        Toast.makeText(MainActivity.this, "CheckBox já não está ativada!", Toast.LENGTH_SHORT).show();

    }
});
    
asked by anonymous 28.04.2015 / 12:35

2 answers

3

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();
    }
}
    
28.04.2015 / 15:06
2

My suggestion is very simple, use Timer to run a scan task at certain times:

private static final long INTERVAL = 4000l;

Timer mTimer;
Button mButton;
Checkbox mCheckbox;

TimerTask mVerifyTask = new TimerTask() {
    @Override
    public void run() {
        verificarCheckbox();
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Realizar sua inicializacao

    mTimer = new Timer();

    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mTimer.cancel();
            mTimer.scheduleAtFixedRate(mVerifyTask, INTERVAL);
        }
    });

void verificarCheckbox() {
    if(mCheckbox.isChecked()) {
        if(Looper.myLooper() != Looper.getMainLooper()) {
            runOnUiThread(new Runnable() { notificarNaMainThread });
        } else {
            notificarNaMainThread();
        }
    }
}

void notificarNaMainThread() {
    Toast.makeText(MainActivity.this, "CheckBox está ativada!", Toast.LENGTH_SHORT).show();
}

A note : Changes of View's out of MainThread are not allowed, but state queries are allowed. If there is no use of the verificarCheckbox method to be used in the Timer and outside it, then

if(Looper.myLooper() != Looper.getMainLooper()) {

is not necessary and can be simplified.

    
28.04.2015 / 14:47