为什么位置应用程序崩溃

时间:2015-02-02 02:06:36

标签: android null crash

我正在尝试使用GoogleMap显示我当前的位置。只要地点位置良好,它就能很好地运行。打开电话(galaxy s4)。但是当我关掉这个位置时,它会崩溃。通话中。

Logcat告诉提供者在以下行中为空

Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));

我想弹出一条消息,说明打开位置"而不是崩溃应用程序。什么是简单的&很好的方法吗?

代码:

public class MapsActivity extends FragmentActivity {

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.
    private Marker marker;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        setUpMapIfNeeded();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }


    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }


    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(32, 270)).title("Marker"));
        mMap.setMyLocationEnabled(true);


        LocationManager locationManager= (LocationManager) getSystemService(Context.LOCATION_SERVICE);


          Criteria criteria = new Criteria();

           Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));

            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 14));


        }
}

1 个答案:

答案 0 :(得分:0)

如果禁用了位置服务,则此调用locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false)); 会返回null。您的应用已崩溃,因为您没有检查location变量是否为null