2010-08-22 70 views
3

我有以下代碼,我希望能夠每30秒循環一次。Android線程問題

MyLocation myLocation = new MyLocation(); 
    public LocationResult locationResult = new LocationResult() { 
     @Override 
     public void gotLocation(final Location location) { 
      GeoPoint myGeoPoint = new GeoPoint(
        (int) (location.getLatitude() * 1000000), 
        (int) (location.getLongitude() * 1000000)); 
      myMapController.animateTo(myGeoPoint); 
      myMapController.setZoom(10); 

      lat = location.getLatitude(); 
      lon = location.getLongitude(); 

      new OverlayTask().execute(); 


      Timer timer; 
      timer = new Timer(); 
      timer.scheduleAtFixedRate(new MyTimerTask(), 30000, 30000); 
     } 

    }; 

被炒魷魚一旦我有位置,和OverlayTask執行罰款,它時,分配給一個菜單項,迫使它也將執行。

但是在計時器中,我收到一個錯誤。

public class MyTimerTask extends TimerTask { 
    public void run() { 
     try { 
      Log.i(">>>>>>>>>>>> Refresh: ", "Success"); 
      new OverlayTask().execute(); 
     } catch (Exception e) { 
      Log.e(">>>>>>>>>>>> Error executing MyAsyncTask: ", e.getMessage(), e); 
     } 
    } 
} 

該錯誤是....

錯誤執行MyAsyncTask:(2573):只有創建視圖層次可以觸摸其意見原來的線程。

回答

3

使用runOnUiThread方法:

public class MyTimerTask extends TimerTask { 
    public void run() { 
     runOnUIThread(new Runnable(){ 
      public void run(){ 
       try { 
        Log.i(">>>>>>>>>>>> Refresh: ", "Success"); 
        new OverlayTask().execute(); 
       } catch (Exception e) { 
        Log.e(">>>>>>>>>>>> Error executing MyAsyncTask: ", e.getMessage(), e); 
       } 
      } 
     }); 
    } 
}