繁体   English   中英

animateCamera,IllegalStateException:不在主线程上

[英]animateCamera, IllegalStateException: Not on the main thread

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

        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保留在地图类内的同一函数中。 我已经有来自主应用程序的主上下文可以在此类中用作变量,我可以利用它并使它工作吗?

实际上,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);

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

您可以使用HandlerrunOnUiThread()post()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM