简体   繁体   English

在 UI 线程中删除已发送的消息

[英]Deleting sent messages in UI thread

Let me elaborate a little bit more for example if I have this code:让我详细说明一下,例如,如果我有以下代码:

This object is created by the main UI thread:该对象由主 UI 线程创建:

Handler handler= new Handler();

Then I use:然后我使用:

handler.postDelayed(new Runnable(){
}, 1000);

My question is, can I cancel that action so that if posted to the main thread's message queue?我的问题是,如果发布到主线程的消息队列,我可以取消该操作吗?

You can remove previously posted Runnables using the removeCallbacks() method on the Handler used to post them.您可以使用用于发布它们的处理程序上的removeCallbacks()方法删除以前发布的 Runnable。 You will need to have the exact reference to the Runnable posted.您需要准确引用发布的 Runnable。

In your code, you post a Runnable while declaring it anonymously inline.在您的代码中,您发布了一个 Runnable,同时匿名内联声明它。 If you do that, won't retain a reference to that Runnable.如果这样做,将不会保留对该 Runnable 的引用。 Instead, you can store the reference to that new Runnable in a member variable or something that won't be forgotten by the time you want to remove it.相反,您可以将对该新 Runnable 的引用存储在成员变量中,或者在您想要删除它时不会忘记的东西中。

private Runnable r;  // assign before use
private Handler h;   // assign before use

private void schedule() {
    h.postDelayed(r, 99999);
}

private void cancel() {
    h.removeCallbacks(r);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM