我已经实现了谷歌地图,它工作正常,直到我退出地图活动去另一个活动,当我返回到地图活动时,它然后崩溃。我认为当位置监听器在FIRST地图仍在加载或地图相互重载时尝试获取用户位置时会发生这种情况,那么当我将活动保留在onPause和onDestroy下时,如何销毁我的第一张地图?
请注意,我的类扩展了Activity而不是Fragment或FragmentActivity,我没有使用MapView。
public class ActivityLocate extends Activity
private GoogleMap map;
...
private void initilizeMap() {
lm = (LocationManager)ActivityLocate.this.getSystemService(Context.LOCATION_SERVICE);
ll = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (map == null) {
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
// check if map is created successfully or not
if (map == null) {
Toast.makeText(getApplicationContext(),"Failed to load map", Toast.LENGTH_SHORT).show();
}
}
latitude = location.getLatitude();
longitude = location.getLongitude();
latitudeString = String.valueOf(latitude);
longitudeString = String.valueOf(longitude);
map.setMyLocationEnabled(true);
if (autoCamera.equals("1"))
{
map.animateCamera( CameraUpdateFactory.zoomTo(4.0f) );
CameraUpdate center= CameraUpdateFactory.newLatLng(new LatLng(latitude, longitude)); // zoom to current location
CameraUpdate zoom=CameraUpdateFactory.zoomTo(8);
map.moveCamera(center);
map.animateCamera(zoom);
autoCamera = "0";
}
else
{
//don't position camera again to allow user to self navigate
}
accessWebService_getMarkers();
}
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
};
//LOCATION CHANGE OPTIONS
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 1, ll); //every minute / meter
}
生命周期:
@Override
protected void onResume() {
super.onResume();
if (map == null) {
try {
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
}
错误:
Attempt to invoke virtual method 'com.google.android.gms.maps.GoogleMap com.google.android.gms.maps.MapFragment.getMap()' on a null object reference
答案 0 :(得分:1)
Google地图V2现在不使用getMap,它使用getMapAsync(this);
点击此链接Google Map V2,它将解决您的问题
答案 1 :(得分:1)