我有一个Android服务,正在为我创建一个错误。它可以通过if / else语句运行。基本上,我需要它连续运行检查并连续执行if。它做到了这一点。我需要它一次执行else,直到再次检测到if为止。

我的问题是,它还在循环中运行else进程。如何在检测是否为if的情况下使else语句运行一次?

这是一个代码示例...

         if(mTimer != null) {
            mTimer.cancel();
        } else {
            // recreate new
            mTimer = new Timer();
        }
        // schedule task
        mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
    }



    class TimeDisplayTimerTask extends TimerTask {

        @Override
        public void run() {
            // run on another thread
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    // display toast

                    if(musicActive) {
                     // Set Ringer to vibrate

                  } else {
                        // Set Ringer to Normal


                  }
                }

            });
        }


问题在于,当服务运行且未检测到音乐时,人们无法更改其铃声设置,因为我的应用仍将其保留在服务中。如果我将} else {保留为空,则会得到理想的结果,但是我需要它运行一次该过程才能将振铃器设置为正常。我只需要它每秒一次将振铃器设置为正常。

最佳答案

最简单的方法就是记住,像这样:

 boolean lastWasElse = false;


 mHandler.post(new Runnable() {

       @Override
       public void run() {

           if(true) {
                //  do this
                lastWasElse = false;
           } else if (!lastWasElse) {
                  // do once and then loop again, but if the answer is still "else" then skip this line.
                lastWasElse = true;
           }
       }


问题在于您存储lastWasElse变量的位置-因为您要不断创建新的可运行对象。您需要在中央某个位置存储该变量的一个副本,并在每次任务运行时对其进行检查...

...或不断重复使用相同的Runnable而不是创建新的Runnable并将变量存储在中。

08-05 10:46