Android获取当前位置信息,百分之百有效

private String provider;

    // get current location
    private Location getMyLocation() {
        if (locationManager

                .isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {

locationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, 100, 0, this);

            if (locationManager

                    .isProviderEnabled(android.location.LocationManager.NETWORK_PROVIDER)) {

  locationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 0, 0, this);//这个只要手机联网百分之百能获取到

                Criteria c = new Criteria();
                c.setAccuracy(Criteria.ACCURACY_FINE);
                c.setAltitudeRequired(false);
                c.setBearingRequired(false);
                c.setCostAllowed(true);
                c.setPowerRequirement(Criteria.POWER_LOW);
                provider = locationManager.getBestProvider(c, true);
                Location location = locationManager
                        .getLastKnownLocation(provider);
                if (location != null) {
                    return location;
                }
            } else {
                Toast.makeText(getActivity(), "请连接网络", Toast.LENGTH_LONG)
                        .show();
            }
        } else {
            Toast.makeText(getActivity(), "请打开GPS开关", Toast.LENGTH_LONG).show();
        }
        return null;

    }    

//上面的获取可能为null,下面的绝对不会为null,前提是手机联网

@Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            myLocation = location;
            LogUtils.i("myLocation-changed", "lat:" + myLocation.getLatitude()
                    + "lng:" + myLocation.getLongitude());
        }
    }


你可能感兴趣的:(Android,GPS,获取位置)