2012-11-23 26 views
0

我想觸發定時器線程內的AsynTask,我收到以下錯誤。定時器和異步在一起

java.lang.ExceptionInInitializerError 產生的原因:了java.lang.RuntimeException:無法內螺紋創建處理程序尚未調用Looper.prepare()

是否有可能或不??? 這裏是我的代碼

networkTimer = new Timer(); 
       networkTimer.schedule(new TimerTask() { 
        int counter = 1; 
        @Override 
        public void run() { 
         // TODO Auto-generated method stub 
         if(isNetworkAvailable()){ 
          Log.d("Hey I got the Network","!!"); 
          new GmailAsync().execute(""); 
          networkTimer.cancel(); 
         }else{ 
          Log.d("Attempt","No:"+counter); 
          counter++; 
          if(counter == 6){ 
           Log.d("Attempt","Finished"); 
           networkTimer.cancel(); 
          } 
         } 
        } 
       },0, 5000); 
+0

的http://計算器。 com/questions/10496744/start-asynctask-in-timertask – jnr

+0

我從她的http://stackoverflow.com/questions/10496744/start-asynctask-in-timertask工作很好:) –

回答

0

簡單包裝每次調用FinderMain $ 1.gotLocation或一個Runnable在它創建的AsyncTask,並張貼到綁定到UI線程,這樣的處理程序:

class GetLastLocation extends TimerTask { 
    private Handler mHandler = new Handler(Looper.getMainLooper()); 

     @Override 
     public void run() { 
      // ... 
      mHandler.post(new Runnable() { 
       public void run() { 
        locationResult.gotLocation(null); 
       } 
      }); 
      // ... 
     } 
    } 
+0

這是非常重的,redondant,作爲處理程序可以完全取代計時器和timertask。另外,我沒有看到與問題的任何實際關係。 (沒有asynctask或網絡,爲一個) – njzk2

1

AsyncTask.execute()必須在UI線程,你的TimerTask沒有運行。

建議: *使用runOnUiThread回到UI線程使用您的AsyncTask *不要使用計時器,而是一個處理和postDelyaed *如果你不需要,不要使用的AsyncTask與UI(你可以,但我不知道你的AsyncTask做什麼互動

最好的解決辦法是#2那會是什麼樣子:。

mHandler.postDelayed(new Runnable() { 
    @Override 
    public void run() { 
     if(isNetworkAvailable()){ 
      Log.d("Hey I got the Network","!!"); 
      new GmailAsync().execute(""); 
     }else{ 
      Log.d("Attempt","No:"+counter); 
      counter++; 
      if(counter == 6){ 
       Log.d("Attempt","Finished"); 
      } else { 
       mHandler.postDelayed(this, 5000); 
      } 
     } 
    }, 5000); 
} 

只要計數器< 6,可運行的轉貼本身

+0

唯一的疑問就是如果isNetworkAvailable實際上測試一個網絡連接,在這種情況下,你將有networkonuithread – njzk2