Android:在Asynctask上创建MapView不起作用

时间:2011-08-25 09:28:33

标签: android android-mapview android-asynctask

我正在尝试在另一个线程上创建一个MapView,因为加载一个Activity需要很长时间。

class MapCreation extends AsyncTask<Integer, Void, MapView>
{
    MapActivity context;

    public MapCreation(MapActivity context)
    {
        this.context = context;
    }

    @Override
    protected MapView doInBackground(Integer... params)
    {
        ListView someListView = new ListView(context); //Completely fine!
        MapView someMapView = new MapView(context, OMITTED_KEY); //!!!!CRASH!!!!
        return someMapView;
    }

    protected void onPostExecute(MapView someMapView)
    {
           //do something
    }
}

程序在“ThreadPoolExecutor.class”处停止:

} finally {
    processWorkerExit(w, completedAbruptly);
}

注意:我知道每个进程1个实例的MapActivity / MapView限制。我在执行这个AsyncTask之前没有创建过MapView对象。

2 个答案:

答案 0 :(得分:0)

我从XML文件中提取地图,然后将其推送到布局容器。

public void run() { try {

                    MapsInitializer.initialize(activityHost);

                    LayoutInflater inflater = (LayoutInflater) activityHost.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    mapView = (MapView) inflater.inflate(R.layout.map, mapView, true);

                    mapContainer.addView(mapView);
                    mapView.onCreate(null);
                    mapView.onResume();

                    googleMap = mapView.getMap();
                    if (googleMap == null)
                        return;

                    googleMap.setMyLocationEnabled(false);
                    googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mapLocation, 15.0f));
                    googleMap.getUiSettings().setZoomControlsEnabled(false);
                    googleMap.getUiSettings().setAllGesturesEnabled(false);


                } catch (GooglePlayServicesNotAvailableException e) {
                    Log.e("ERROR", "ERROR -  failed to create map");
                    return;
                }
            }
        }

和地图xml:

<com.google.android.gms.maps.MapView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:id="@+id/some_id"
    android:layout_width="fill_parent"
    android:layout_height="100dp"
    android:apiKey="YOUR_ID"
    android:visibility="visible"
    />

答案 1 :(得分:-1)

首先,我认为您至少需要获取地图的调试密钥,否则您将获得一个空白屏幕

然后,如果您阅读有关构造函数的信息

public MapView(android.content.Context context,
           java.lang.String apiKey)

Constructs a MapView object.

Parameters:
    context - A MapActivity object.
    apiKey - A Google Maps API Key. See Obtaining a Maps API Key for complete information. 
Throws:
    java.lang.IllegalArgumentException - **if the enclosing context is not an instance of MapActivity.**

地图必须扩展MapActivity。