removeCallbacks没有阻止可运行 [英] removeCallbacks not stopping runnable

查看:154
本文介绍了removeCallbacks没有阻止可运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是从一个方法调用:

myHandler.postDelayed(mMyRunnableHide, 6000);

这就要求:

public Runnable mMyRunnableHide = new Runnable()
{

    public void run()
    {
        mTextDisplay.setText("");
        DisplayX();
    }
 };

如果点击屏幕上的一个按钮,我想停下来的可运行:

if a button on screen is clicked I want to stop the runnable:

   Button next = (Button) findViewById(R.id.Breaction);
    next.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {

            myHandler.removeCallbacks(mMyRunnableHide);

            mTextDisplay.setText("");
            DisplayX();
            }
        });   
    }

在removecallbacks没有停止可运行。我究竟做错了什么?我使用正确的方法?我只是想可运行为未运行,当用户点击该按钮。

the removecallbacks is not stopping the runnable. What am I doing wrong? Am I using the correct method? I just want the runnable to "Not Run" when the user clicks the button.

感谢您的帮助。

推荐答案

在我看来,那 removeCallbacks(..)仅停止的挂起的消息(的Runnable)。如果您的可运行已经启动,那么就没有停止它(至少不是这样)。

It appears to me that removeCallbacks(..) only stops pending messages (Runnables). If your runnable has already started, then there's no stopping it (at least not this way).

此外,还可以延长运行的类,并给它某种杀死开关像这样的:

Alternatively, you can extend the Runnable class and give it some kind of kill switch like this:

public class MyRunnable implements Runnable
{
   private boolean killMe = false;

   private void run()
   {
      if(killMe)
         return;

      /* do your work */
   }

   private void killRunnable()
   {
      killMe = true;
   }
}

这将只启动prevent它,但你可以偶尔检查 KILLME 和救助。如果你是循环的可运行(如某种后台线程),你可以说:

This will only prevent it from starting, but you could occasionally check killMe and bail out. If you are looping the runnable (like some kind of background thread) you can say:

while(!killMe) {
   /* do work */
}

希望这有助于

Hope this helps

修改我只是想张贴在此更新。由于这个原来的职位,谷歌已经想出了一个伟大的类称为AsyncTask的处理所有的这些东西给你。阅读本真应该看看它,因为它是做事情的正确方法。

EDIT I just wanted to post an update on this. Since this original post, Google has come up with a great class called AsyncTask that handles all of this stuff for you. Anyone reading this really should look into it because it is the correct way of doing things.

您可以了解它这里

这篇关于removeCallbacks没有阻止可运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆