2011-08-25 82 views
0

我想在另一个线程上创建一个MapView,因为它需要太长时间才能加载活动。Android:在Asynctask上创建MapView不起作用

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对象。

+0

不能从UI比UIThread其他任何线程改变。 –

+0

那么我怎么能够在这个新线程以及其他类型的视图中创建一个ListView(ViewGroup的子类),但是我不能在这个新线程中创建一个MapView(ViewGroup的子类)? – ninjaneer

+0

因为你已经在UI Thread上创建了'RelativeLayout'(虽然名为'setContentView()'),所以现在你要添加一个视图到来自另一个'Thread'的'RelativeLayout',在'onPostExecute (MapView someMapView)' –

回答

-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。

+0

OMITTED_KEY ==我省略的调试密钥。另外,我将一个MapActivity对象传递给构造函数已经是需要的上下文的子类。 – ninjaneer

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" 
    />