首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >looper.prepare问题

looper.prepare问题
EN

Stack Overflow用户
提问于 2011-03-07 21:28:07
回答 2查看 7.7K关注 0票数 1

我试图在计时器中循环一个吐司,但没有显示吐司

logcat中的日志显示无法在未调用looper.prepare()的线程内创建处理程序,我不确定这是什么意思

代码语言:javascript
复制
    int initialDelay = 10000;
    int period = 10000;
    final Context context = getApplicationContext();
    TimerTask task = new TimerTask() 
    {
        public void run() 
        {               
            try
            {
                if (a != "")
                {   
                      Toast toast = Toast.makeText(context, "Alert Deleted!", Toast.LENGTH_SHORT);
                      toast.show();
                }
            }
            catch (Exception e)
            {

            }
        }
    };
    timer.scheduleAtFixedRate(task, initialDelay, period);

我的应用程序每隔10秒就会检查某个变量是否为空。如果它是空的,那么它将显示一个吐司。

我可以在服务类中做到这一点,但是当我尝试将其实现到

代码语言:javascript
复制
 public void onCreate(Bundle savedInstanceState)

我得到了这个错误

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-03-07 22:01:43

您正在从工作线程调用它。您需要从主线程中调用Toast.makeText() (以及处理UI的大多数其他函数)。例如,您可以使用处理程序。

请看这个答案...

Can't create handler inside thread that has not called Looper.prepare()

票数 2
EN

Stack Overflow用户

发布于 2014-07-11 02:57:47

你也可以用不同的方式来展示这个祝酒词

代码语言:javascript
复制
class LooperThread extends Thread {
      public Handler mHandler;

      @Override
      public void run() {
          Looper.prepare();

          mHandler = new Handler() {
              @Override
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
      }
  }

现在,正如您所看到的,这个处理程序是在普通线程中创建的,所以如果您尝试从它发送任何消息,它将抛出一个异常,因此通过使用Looper.prepare()和Looper.loop()绑定它,您可以在UI线程上执行在它内部执行的任何语句

另一个例子

循环允许在单个线程上顺序执行任务。处理程序定义了我们需要执行的那些任务。这是一个典型的场景,我尝试在示例中进行说明:

代码语言:javascript
复制
class SampleLooper {
@Override
public void run() {
  try {
    // preparing a looper on current thread     
    // the current thread is being detected implicitly
    Looper.prepare();

    // now, the handler will automatically bind to the
    // Looper that is attached to the current thread
    // You don't need to specify the Looper explicitly
    handler = new Handler();

    // After the following line the thread will start
    // running the message loop and will not normally
    // exit the loop unless a problem happens or you
    // quit() the looper (see below)
    Looper.loop();
  } catch (Throwable t) {
    Log.e(TAG, "halted due to an error", t);
  } 
}
}

现在,我们可以在其他一些线程(比如UI线程)中使用该处理程序来将任务发布到Looper上执行。

代码语言:javascript
复制
handler.post(new Runnable()
{
public void run() {`enter code here`
//This will be executed on thread using Looper.`enter code here`
    }
});

在UI线程上,我们有一个隐式循环,它允许我们在UI线程上处理消息。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5220277

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档