使用GPS时,Google地图活动会崩溃

时间:2014-12-27 18:51:29

标签: android gps maps

我搜索了这个问题的答案差不多2个小时,但我找不到解决办法。问题是我想使用设备GPS创建谷歌地图活动,如果它关闭,请让用户激活它。我面临的问题是每次我想打开活动时都会崩溃。我正在测试一个真实的设备。

这是我的代码:

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.
    public double latitude;
    public double longitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pantalla_hospitales_farmacias_cerca);
        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() {

        // Enable MyLocation Layer of Google Map
        mMap.setMyLocationEnabled(true);

        // Create a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // // Get LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))  buildAlertMessageNoGps();

        // Get the name of the best provider
        locationManager.getBestProvider(criteria, true);

        // Get Current Location
        Location myLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        // set map type
        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

        // Get latitude of the current location
        latitude = myLocation.getLatitude();

        // Get longitude of the current location
        longitude = myLocation.getLongitude();

        // Create a LatLng object for the current location
        LatLng latLng = new LatLng(latitude, longitude);

        // Show the current location in Google Map
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        // Zoom in the Google Map
        mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
        mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("Estás aquí").snippet("Farmacias y hospitales cercanos"));

        // request that the provider send this activity GPS updates every 20 seconds
        //locationManager.requestLocationUpdates(provider, 20000, 0, this);

    }

    @Override
    public void onLocationChanged(Location location) {
        mMap.clear();
        longitude = location.getLongitude();
        latitude = location.getLatitude();
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    // function that opened an activity to turn on the GPS
    private void buildAlertMessageNoGps() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("El GPS está desactivado. ¿Quiere activarlo? ")
                .setCancelable(true)
                .setPositiveButton("Sí.",
                        new DialogInterface.OnClickListener() {
                            public void onClick(final DialogInterface dialog, final int id) {
                                startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                            }
                        })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int id) {
                        dialog.cancel();
                        PantallaHospitalesFarmaciasCerca.this.finish();
                    }
                });
        final AlertDialog alert = builder.create();
        alert.show();
    }


}

如果我使用的话就是:

String provider = locationManager.getBestProvider(criteria, true);
Location myLocation = locationManager.getLastKnownLocation(provider);

而不是我现在使用的是什么,但不是GPS,它适用于网络位置。我怎么能只使用GPS工作呢? 非常感谢你。

1 个答案:

答案 0 :(得分:0)

当您致电getLastKnownLocation时,结果可能为空:

  

如果当前禁用了提供程序,则返回null。

检查时

if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))  buildAlertMessageNoGps();

该块之后的代码仍然执行,因此在禁用GPS时仍会调用getLastKnownLocation。考虑使用else块来防止这种情况。

相关问题