Search code examples
androidswitch-statementcountdowntimertoggleswitch

How to automatically turn a switch button on/off every 15 seconds?


Hi in the below code i have one switch button .without checked/unchecked switch button want to do on or off operations for every 15min

With ischecked it was working.but want without touching that switch automatically should happens

can any one please help me

  geyserOnOff.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {

                    Log.d(TAG, "Checked once programatically :" + isProgrammatically);
                    if (!isProgrammatically) {

                        if (isChecked) {
                            /*geyser on method*/

                            geyserOnMethod();


                        } else {
                            if (ConstantUtils.REMAINING_DURATION_TIMER > 0) {
                                /*timer running alert dilaog*/
                                timerRunningAlertDialog();

                            } else if (isTimerRunning) {
                                 /*timer running alert dilaog*/

                                timerRunningAlertDialog();
                            } else {
                                /*geyser off method*/
                                long millisInfuture=15000;
                                long countDownInterval=1000;
                                new CountDownTimer(millisInfuture,countDownInterval){
                                    public void onTick(long millisUntilFinished){
                                        Toast.makeText(context,"Seconds Remaining:"+millisUntilFinished/1000,Toast.LENGTH_LONG).show();
                                    }
                                    public void onFinish(){
                                        Toast.makeText(context,"Time Over",Toast.LENGTH_LONG).show();
                                    }
                                }.start();
                                geyserOffMethod();

                            }


                        }
                    }
                    isProgrammatically = false;
                }
            });

Solution

  • You can proceed to use a TimerTask! Set the timer for 15 seconds and in execution toggle the checkbox and reset the timer again for 15 seconds.

        Timer timer = new Timer();
        final TimerTask task = new TimerTask() {
               @Override
               public void run() {
                   myCheckBox.setChecked(!myCheckBox.isChecked()); //Toggle
               }
           };
        timer.scheduleAtFixedRate(task, 15*1000, 15*1000); //Schedule from delay 15 seconds
       //schedule