java.lang.IllegalStateException:不在主线程谷歌地图上

时间:2016-09-05 13:29:46

标签: android google-maps

当我的Android应用代码从云消息传递平台接收数据并尝试将数据放在地图上时,我收到了上述错误 -

    java.lang.IllegalStateException: Not on the main thread
    at maps.w.c.a(Unknown Source)
    at maps.y.F.a(Unknown Source)
    at maps.ad.u.b(Unknown Source)
    at vo.onTransact(:com.google.android.gms.DynamiteModulesB:92)
    at android.os.Binder.transact(Binder.java:380)
    at com.google.android.gms.maps.internal.IGoogleMapDelegate$zza$zza.animateCamera(Unknown Source)
    at com.google.android.gms.maps.GoogleMap.animateCamera(Unknown Source)
    at com.pabba.mtracker.tracking.view.TrackingActivity.onLocationReceived(TrackingActivity.java:54)

以下是我的演示者(我正在使用我的Android应用程序的MVP模式)调用的代码,当它从云消息传递服务收到位置消息时。

@Override
public void onLocationReceived(LatLng latLng) {
    Log.i(TAG, latLng.toString());
    mGoogleMap.addPolyline(new PolylineOptions().add(latLng));
    mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder().target(latLng)
            .zoom(13).build()));
}

错误发生在addPolyLine函数调用中。 请告诉我如何解决它。

2 个答案:

答案 0 :(得分:7)

您必须在UIThread中运行此代码:

activity.runOnUIThread(new Runnable(){
    public void run(){
        mGoogleMap.addPolyline(new PolylineOptions().add(latLng));
        mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder().target(latLng)
        .zoom(13).build()));
    }
});

答案 1 :(得分:0)

以下代码将为您提供帮助。添加您的活动。

runOnUiThread(new Runnable() {
   @Override
   public void run() {
      MapView mMapView = (MapView) dialog.findViewById(R.id.mapView);
      MapsInitializer.initialize(context);
      mMapView.onCreate(dialog.onSaveInstanceState());
      mMapView.onResume();
      mMapView.getMapAsync(new OnMapReadyCallback() {
      @Override
      public void onMapReady(final GoogleMap googleMap) {
            LatLng myLocation=new LatLng(Double.parseDouble(lat), Double.parseDouble(lon));
            googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
            googleMap.addMarker(new MarkerOptions().position(myLocation).title("My location").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
            float zoomLevel = (float) 16.0; //This goes up to 21
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLocation, zoomLevel));  
            googleMap.getUiSettings().setZoomControlsEnabled(true);
         }
      });
   }
});