looper.prepare问题

时间:2011-03-07 13:28:07

标签: android

我正在尝试在计时器内循环吐司但吐司不显示

登录logcat显示无法在未调用looper.prepare()的线程内创建处理程序我不知道这意味着什么

    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秒检查某个变量是否为空。如果它是空的,那么它将显示一个祝酒词。

我在服务类中执行此操作没有问题但是当我尝试将其实现到

 public void onCreate(Bundle savedInstanceState)

我收到此错误

2 个答案:

答案 0 :(得分:2)

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

看到这个答案......

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

答案 1 :(得分:0)

你也可以用其他方式展示这种吐司

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线程上执行的语句

另一个例子

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

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上发布任务来执行。

handler.post(new Runnable()
{
public void run() {`enter code here`
//This will be executed on thread using Looper.`enter code here`
    }
});

在UI线程上,我们有一个隐式Looper,允许我们处理ui线程上的消息。