如何每15秒自动打开/关闭一个开关按钮?

时间:2018-12-06 07:19:37

标签: android switch-statement countdowntimer toggleswitch

您好,在下面的代码中,我有一个开关按钮。未选中/未选中的开关按钮希望每15分钟执行一次打开或关闭操作

选中is可以正常工作,但是希望在不触摸该开关的情况下自动发生

任何人都可以帮助我

  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;
                }
            });

1 个答案:

答案 0 :(得分:1)

您可以继续使用TimerTask! 将计时器设置为15秒,然后在执行时切换复选框并再次重置计时器15秒。

    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