animateCamera,IllegalStateException:不在主线程上

时间:2014-06-22 17:26:55

标签: java android google-maps

我有单独的地图类,其中我编写了与地图活动相关的所有逻辑,因为严格要求将两个地图相关的事物分开。现在从主应用程序活动我调用这样的函数:

        Timer t = new Timer();
        t.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                if (mapObj.isLocationClientConnected)
                    Location currentLocation = mapObj.gotoCurrentLocation();

            }

        }, 0, refreshUserLocationInterval);

Map Class我有:

public Location gotoCurrentLocation() {
    currentLocation = mLocationClient.getLastLocation();
        LatLng ll = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
        CameraUpdate cUpdate = CameraUpdateFactory.newLatLngZoom(ll, defaultZoom);
        gMap.animateCamera(cUpdate);

    return currentLocation;

}

但是我收到了这个错误:

06-22 19:56:30.900: E/AndroidRuntime(11413): FATAL EXCEPTION: Timer-0
06-22 19:56:30.900: E/AndroidRuntime(11413): java.lang.IllegalStateException: Not on the main thread
06-22 19:56:30.900: E/AndroidRuntime(11413):    at kbh.b(Unknown Source)
06-22 19:56:30.900: E/AndroidRuntime(11413):    at lzd.b(Unknown Source)
06-22 19:56:30.900: E/AndroidRuntime(11413):    at mbi.b(Unknown Source)
06-22 19:56:30.900: E/AndroidRuntime(11413):    at fms.onTransact(SourceFile:92)
06-22 19:56:30.900: E/AndroidRuntime(11413):    at android.os.Binder.transact(Binder.java:310)
06-22 19:56:30.900: E/AndroidRuntime(11413):    at com.google.android.gms.maps.internal.IGoogleMapDelegate$a$a.animateCamera(Unknown Source)
06-22 19:56:30.900: E/AndroidRuntime(11413):    at com.google.android.gms.maps.GoogleMap.animateCamera(Unknown Source)
06-22 19:56:30.900: E/AndroidRuntime(11413):    at com.mapworlds.mapworlds.MapClass.gotoCurrentLocation(MapClass.java:176)

我想将animateCamera保留在map类中的相同函数中。我已经将主应用程序的主要上下文作为此类中的变量提供,我可以使用它并使其工作吗?

2 个答案:

答案 0 :(得分:5)

实际上,animateCamera会修改UI组件(地图),因此必须在UI线程上完成。

修改

你可以这样做:

Timer t = new Timer();
        t.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
             runOnUiThread(new Runnable() 
             {
              public void run() 
              {  
                //update ui
                if (mapObj.isLocationClientConnected)
                    Location currentLocation = mapObj.gotoCurrentLocation();

              }
             });
           }
        }, 0, refreshUserLocationInterval);

答案 1 :(得分:3)

您需要从主线程中调用animateCamera()

您可以使用HandlerrunOnUiThread()post()进行此操作。