2012-12-05 30 views
0

我正在一個Android應用程序。在我的活動我使用下面的代碼。Asynctask導致異常'不能創建處理程序內部線程沒有調用Looper.prepare()'

LocationResult locationResult = new LocationResult(){ 

     @Override 
     public void gotLocation(Location location){ 
      //Got the location! 




      Drawable marker = getResources().getDrawable(
        R.drawable.currentlocationmarker);//android.R.drawable.btn_star_big_on 
      int markerWidth = marker.getIntrinsicWidth(); 
      int markerHeight = marker.getIntrinsicHeight(); 
      marker.setBounds(0, markerHeight, markerWidth, 0); 
      MyItemizedOverlay myItemizedOverlay = new MyItemizedOverlay(marker); 
      currentmarkerPoint = new GeoPoint((int) (location.getLatitude() * 1E6), 
        (int) (location.getLongitude() * 1E6)); 

      currLocation = location; 

      mBlippcoordinate = currentmarkerPoint; 
      mBlippLocation = location; 
      myItemizedOverlay.addItem(currentmarkerPoint, "", ""); 

      mBlippmapview.getOverlays().add(myItemizedOverlay); 
      animateToCurrentLocation(currentmarkerPoint); 


     } 
    }; 


    MyLocation myLocation = new MyLocation(); 
    myLocation.getLocation(this, locationResult); 

我使用的上述代碼,以查找從GPS或網絡.The位置animateToCurrentLocation(currentmarkerPoint);方法包含的AsyncTask。所以我提前得到

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

感謝。

+2

我打賭你在你的asynctask中有某種對話或吐司:)你需要重新排列你的代碼,這樣你纔不會從UI – vodich

回答

3

當您嘗試從沒有附加Looper的線程創建並運行AsyncTask時,會出現此錯誤。 AsyncTasks需要Looper在啓動AsyncTask的線程上重新發布它的「任務完成」消息。

現在你真正的問題:如何獲得一個Looper線程?事實證明,你已經有一個:主線程。正如文檔中所述,您應該從主線程創建並執行()您的AsyncTask。 doInBackground()然後將運行在一個工作線程上(來自AsyncTask線程池),並且你可以在那裏訪問網絡。然後onPostExecute()將在主線程上通過主線程的Handler/Looper發佈後在主線程上運行。

+0

+1中進行網絡操作以獲得很好的解釋。 – Madushan

+0

@baske ....我明白了一些..但不知道如何解決我目前的問題..現在我的asynctask從線程調用。我如何使我的asynctask任務從主線程工作?... –

+0

如果我正確地理解你,你現在正在創建和執行你的AsyncTask從一個工作線程,你想知道怎麼做,而不是在主線程?那麼我能想到的最卑鄙的方式就是使用Activity的runOnUiThread()方法。 您當前的代碼(樣機代碼,實際上並不工作;-): ... task = new AsyncTask(); task.execute() ... 你的新代碼: ... runOnUiThread(新的Runnable(){@Override 公共 無效的run(){ 任務=新的AsyncTask(); task.execute (); }); ... – baske

相關問題