2011-03-07 34 views
1

我試圖環舉杯定時器內,但敬酒不顯示looper.prepare問題

在日誌中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) 

這個我得到這個錯誤

回答

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線程中的消息。