android 运行 当另一个重复任务完成时重复任务

android run a repeated task when another repeated task is finished

我有一个任务执行 10 秒,周期为 1 秒,没有延迟,另一个任务执行 30 秒,周期为 5 秒,当第一个任务完成时。

此外,我需要在按下按钮时取消这两个任务。

我不知道哪个是这个问题的最佳解决方案。

  1. 我尝试了基本线程,但会阻塞 GUI,直到两个任务都完成 执行
  2. 我试过 ExecutorService executorService = Executors.newSingleTheadExecutor() 但我这种情况 executor.submit(runnable) 一个接一个地执行任务但不执行 每个定期

  3. 我尝试了按固定速率安排的预定执行程序,但是 scheduled executor 是异步的,我知道如何使用

    executorService.scheduleAtFixedRate(runnable1, delay, period);      
    //and after finished to run
    executorService.scheduleAtFixedRate(runnable2, delay, period);
    

欢迎任何反馈。

此致, AurelianR

您可以使用 AlarmManager 来完成重复的任务。

或者您可以使用 AsyncTask。它允许您在不阻塞 UI 线程的情况下在后台工作,然后在必要时更新 UI。

可以使用CountDownTimerclass。我模拟了一个简单的演示。

我创建了几个 Runnable 任务来模拟 VolumeUp 和 VolumeDown 函数。

timerUp 启动时,它会计算给定的时间。 timerUp 计数完成后,在 onFinish 中开始 timerDown。倒计时了。

public class TimerActivity extends AppCompatActivity {

    private TextView out;
    int value = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_timer);

        out = (TextView) findViewById(R.id.out);
        setText(value);

        timerUp.start();
    }

    CountDownTimer timerUp = new CountDownTimer(10000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            runnable1.run();
        }

        @Override
        public void onFinish() {
            timerDown.start();
        }
    };

    CountDownTimer timerDown = new CountDownTimer(10000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            runnable2.run();
        }

        @Override
        public void onFinish() {
            Log.e("done", "onFinish");
        }
    };

    private void setText(final int value){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                out.setText(String.valueOf(value));
            }
        });
    }

    Runnable runnable1 = new Runnable() {
        @Override
        public void run() {
            value += 10;
            setText(value);
        }
    };

    Runnable runnable2 = new Runnable() {
        @Override
        public void run() {
            value -= 10;
            setText(value);
        }
    };
}

定时器可以通过调用取消,

timerUp.cancel();
timerDown.cancel();

您可能需要稍微调整一下时间值。希望你明白了。祝你好运。 :)

martinkbrown 和 K Neeraj Lal 对此提供了一些很好的答案,这将在您的特定情况下有所帮助(您需要使用异步线程来防止阻塞 UI 线程),但是为了响应诸如此类的事件这些你应该考虑为你的项目整体采用 ReactiveX 方法。它简化了整个应用程序代码中有关精心定时的事件的通信。这是一个更大规模的补充,涉及学习使用开源库,但会加快您从现在开始的开发。

http://reactivex.io/ and https://github.com/ReactiveX/RxAndroid 了解更多信息

或另一个不错的选择: https://github.com/greenrobot/EventBus