我使用了一个处理程序,该处理程序通过Runnable发布了一些postDelayed(r, DELAY_TIME),但是我需要先执行所有Runnables,然后再通过postDelayed发布新的。

有什么好主意如何尽可能简单地实现这一目标?

编辑:

我基本上想要这样:

Runnable r = new Runnable() {
    // Do some fancy action
};

if (mHandler.runnablesScheduled) {
    mHandler.flushAllScheduledRunnables();
}
mHandler.postDelayed(r, DELAY);

最佳答案

在数组中,跟踪将要调用的可运行对象,然后,如果希望它们被调用,则取消postDelayed并直接调用可运行对象,要触发它们,只需从可运行对象中调用run()方法即可。示例代码:

// Declaring the Handler and the Array that is going to track Runnables going to be tracked.
final mHandler = new Handler();
final List<Runnable> callStack = new ArrayList<Runnable>();

// Method to remove a runnable from the track Array.
public void removePostDelayed(Runnable run) {
    callStack.remove(run);
}

// Method that we use in exchange of mHandler.postDelayed()
public void myPostDelayed(Runnable run, int delay) {
    // I remove callbacks because I don't know if can be called 2 times.
    mHandler.removeCallbacks(run);

    // We remove the Runnable from the tracking Array just in case we are going to add a Runnable that has not been called yet.
    removePostDelayed(run);

    // We add the runnable to the tracking Array and then use postDelayed()
    callStack.add(run);
    mHandler.postDelayed(run, delay);
}

// This is the Runnable. IMPORTANT: Remember to remove the Runnable from the tracking Array when the Runnable has been called.
Runnable myRunnable = new Runnable() {
    @Override
    public void run() {
        // Do some fancy stuff and remove from the tracking Array.
        removePostDelayed(this);
    }
}

// Method to execute all Runnables
public void callAllStack() {
    // We create a copy of the tracking Array because if you modify the Array while you are iterating through it, will return an Exception.
    List<Runnable> callStackCopy = new ArrayList<Runnable>();

    // here we copy the array and remove all callbacks, so they are not called by the Handler.
    for (Runnable runnable : callStack) {
        callStackCopy.add(runnable);
        mHandler.removeCallbacks(runnable);
    }

    // Then we call all the Runnables from the second Array
    for (Runnable runnable : callStackCopy) {
        runnable.run();
    }

    // And clear the tracking Array because the Handler has no more Runnables to call (This is redundant because supposedly each run() call removes himself from the tracking Array, but well... just in case we forgot something).
    callStack.clear();
}

// Example of postDelaying a Runnable while tracking if has been fired.
myPostDelayed(myRunnable, 1000)

// Example of firing all Runnables.
callAllStack();

非常简单,我已经对其进行了评论,以便您可以更好地理解它,但是如果您不了解某些内容,请对其进行评论。您可以对其进行修改,以支持对同一Runnable的多次调用,也可以只创建自己的Handler的类扩展,即称为TrackingHandler的Handler,并实现这些功能或类似的功能。

我现在正在即时编写代码,因此可能会产生很多错别字,这是不知道的。

关于android - 在处理程序中执行所有计划的(postDelayed)可运行对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16244273/

10-08 21:39