2011-08-25 57 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" 
    />