我有一个Handler从我的子活动被主活动调用。这个处理程序被子类用来postDelay一些可运行对象,我不能管理它们。现在,在onStop事件中,我需要在完成活动之前删除它们(不知何故我调用了finish(),但它仍然一次又一次地调用)。有没有办法从处理程序中删除所有回调?


当前回答

删除特定的可运行对象

handler.removeCallbacks(yourRunnable)

删除所有可运行程序

handler.removeCallbacksAndMessages(null)

其他回答

正如josh527所说,handler.removeCallbacksAndMessages(null);可以工作。 但是为什么呢? 如果您看一下源代码,就可以更清楚地理解它。 有3种类型的方法可以从处理器(MessageQueue)中删除回调/消息:

通过回调(和令牌)删除 通过留言删除。什么(和标志) 通过令牌删除

java(留下一些重载方法)

/**
 * Remove any pending posts of Runnable <var>r</var> with Object
 * <var>token</var> that are in the message queue.  If <var>token</var> is null,
 * all callbacks will be removed.
 */
public final void removeCallbacks(Runnable r, Object token)
{
    mQueue.removeMessages(this, r, token);
}

/**
 * Remove any pending posts of messages with code 'what' and whose obj is
 * 'object' that are in the message queue.  If <var>object</var> is null,
 * all messages will be removed.
 */
public final void removeMessages(int what, Object object) {
    mQueue.removeMessages(this, what, object);
}

/**
 * Remove any pending posts of callbacks and sent messages whose
 * <var>obj</var> is <var>token</var>.  If <var>token</var> is null,
 * all callbacks and messages will be removed.
 */
public final void removeCallbacksAndMessages(Object token) {
    mQueue.removeCallbacksAndMessages(this, token);
}

java做真正的工作:

void removeMessages(Handler h, int what, Object object) {
    if (h == null) {
        return;
    }

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        while (p != null && p.target == h && p.what == what
               && (object == null || p.obj == object)) {
            Message n = p.next;
            mMessages = n;
            p.recycleUnchecked();
            p = n;
        }

        // Remove all messages after front.
        while (p != null) {
            Message n = p.next;
            if (n != null) {
                if (n.target == h && n.what == what
                    && (object == null || n.obj == object)) {
                    Message nn = n.next;
                    n.recycleUnchecked();
                    p.next = nn;
                    continue;
                }
            }
            p = n;
        }
    }
}

void removeMessages(Handler h, Runnable r, Object object) {
    if (h == null || r == null) {
        return;
    }

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        while (p != null && p.target == h && p.callback == r
               && (object == null || p.obj == object)) {
            Message n = p.next;
            mMessages = n;
            p.recycleUnchecked();
            p = n;
        }

        // Remove all messages after front.
        while (p != null) {
            Message n = p.next;
            if (n != null) {
                if (n.target == h && n.callback == r
                    && (object == null || n.obj == object)) {
                    Message nn = n.next;
                    n.recycleUnchecked();
                    p.next = nn;
                    continue;
                }
            }
            p = n;
        }
    }
}

void removeCallbacksAndMessages(Handler h, Object object) {
    if (h == null) {
        return;
    }

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        while (p != null && p.target == h
                && (object == null || p.obj == object)) {
            Message n = p.next;
            mMessages = n;
            p.recycleUnchecked();
            p = n;
        }

        // Remove all messages after front.
        while (p != null) {
            Message n = p.next;
            if (n != null) {
                if (n.target == h && (object == null || n.obj == object)) {
                    Message nn = n.next;
                    n.recycleUnchecked();
                    p.next = nn;
                    continue;
                }
            }
            p = n;
        }
    }
}

删除特定的可运行对象

handler.removeCallbacks(yourRunnable)

删除所有可运行程序

handler.removeCallbacksAndMessages(null)

定义一个新的处理程序和runnable:

private Handler handler = new Handler(Looper.getMainLooper());
private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // Do what ever you want
        }
    };

呼叫延迟:

handler.postDelayed(runnable, sleep_time);

从你的处理器中移除你的回调函数:

handler.removeCallbacks(runnable);

没有一个解决方案对我有效。但我找到了一个有效的解决办法。

即使在调用handler. removecallbacksandmessages (null)之后,已经添加到处理程序队列中的可运行对象也会被执行。当我试图停止线程时,它导致了错误:

W/MessageQueue(6436): java.lang.RuntimeException: Handler (android.os.Handler) {416659f0}发送消息到死线程上的Handler

我的解决方案:

To remove all the callbacks. you need the reference for all the runnables which can be stored in an ArrayList. private ArrayList<Runnable> runnableQueue=new ArrayList<Runnable>(); Then every time u want to post a runnable, store it in the array, then post the array item using handler.post(). private void postInHandler(){ @override runnableQueue.add(new Runnable() { public void run() { //your code } }); //Post the last item in the array handler.post(runnableQueue.get(runnableQueue.size()-1)); } Then to remove all the callbacks use this method which will remove each callback by iterating through the array. private void removeHandlerCallbacks(){ for(Runnable runnable:runnableQueue){ networkHandler.removeCallbacks(runnable,null); } runnableQueue.clear(); } Hurray! the queue is cleared. But wait. After clearing the array we have to make sure that no more runnable is posted in the handler before you stop the thread. So you have to declare: boolean allowPosting=true;

所以要包括这些:

private void removeHandlerCallbacks(){           
    allowPosting=false;//add this line to stop posting after clearing the array
    for(Runnable runnable:runnableQueue){
        handler.removeCallbacks(runnable,null);
    }
     //Dont forget to clear the array
     runnableQueue.clear();
}

然后在提交到处理程序之前检查条件:

if(allowPosting){
    postInHandler();
}

这就是全部,现在队列被清除,我们确定在清除队列后没有更多的可运行对象被发布。所以停止线程是安全的。

对于任何特定的可运行实例,调用Handler.removeCallbacks()。注意,它使用Runnable实例本身来决定取消哪些回调,因此,如果每次发布帖子时都要创建一个新实例,则需要确保对要取消的Runnable的引用是准确的。例子:

Handler myHandler = new Handler();
Runnable myRunnable = new Runnable() {
    public void run() {
        //Some interesting task
    }
};

你可以调用myHandler。postDelayed(myRunnable, x)在你的代码中的其他地方发布另一个回调到消息队列,并使用myHandler.removeCallbacks(myRunnable)删除所有挂起的回调

不幸的是,你不能简单地“清除”处理程序的整个MessageQueue对象,即使你请求与它关联的MessageQueue对象,因为添加和删除项目的方法是包保护的(只有类在android。OS包可以调用它们)。你可能需要创建一个瘦Handler子类来管理一个Runnables列表,因为它们被发布/执行了…或者看看在每个活动之间传递消息的另一个范例

希望有帮助!