2013-08-02 20 views
2

映射我想改變地圖的位置在谷歌地圖V2一套地圖的TimerTask

但香港專業教育學院做了在一個TimerTask ...目標,縮放,方位等,它說

「IllegalStateException異常 - ?不是在主線程

我應該怎麼做任何幫助

class Task extends TimerTask { 

    @Override 
    public void run() { 
     CameraPosition cameraPosition = new CameraPosition.Builder() 
       .target(Zt)  // Sets the center of the map to Mountain View 
       .zoom(12)     // Sets the zoom 
       .bearing(180)    // Sets the orientation of the camera to east 
       .tilt(30)     // Sets the tilt of the camera to 30 degrees 
       .build();     // Creates a CameraPosition from the builder 

     mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); 
    } 
} 

Timer timer = new Timer(); 

timer.scheduleAtFixedRate(new Task(), 0, 20000); 
+0

您無法更新主/ UI線程之外的用戶界面。這可能有所幫助:http://stackoverflow.com/questions/7010951/error-updating-textview-from-timertasks-run-method – Marcelo

+1

非常感謝 - 它的作品:) –

回答

0

定時器任務在不同的線程比UI線程運行在Android中,你是。不允許從非UI線程執行UI操作。使用runOnUiThread方法將操作發送到UI線程:

class Task extends TimerTask { 

    @Override 
    public void run() { 
     runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       CameraPosition cameraPosition = new CameraPosition.Builder() 
         .target(Zt)  // Sets the center of the map to Mountain View 
         .zoom(12)     // Sets the zoom 
         .bearing(180)    // Sets the orientation of the camera to east 
         .tilt(30)     // Sets the tilt of the camera to 30 degrees 
         .build();     // Creates a CameraPosition from the builder 

       mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); 
      } 
     }); 
    } 
} 

Timer timer = new Timer(); 

timer.scheduleAtFixedRate(new Task(), 0, 20000);