getLastKnownLocation有时会返回null

时间:2017-07-18 12:31:29

标签: android location android-gps

首先,我要承认,当您搜索此特定问题时,会有很多结果。然而,根据那些答案,我没有尝试过任何事情。有时我会得到这个位置,有时候我不会。如果我使用Location启用/停用,则在致电null时始终会getLastKnownLocation。如果我有时手动撤消Location权限并再次启用它,则可以正常工作。我尝试将LocationManager更改为location = locationManager .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);,但它无效。

基本上,我正在做以下事情:

    public class GPSTracker implements LocationListener {

    public static final int LOCATION_SETTINGS_REQUEST_CODE = 109;

    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60;

    private static boolean isGpsStatusChanged = false;
    private static AlertDialog.Builder alertDialog;

    private LocationManager locationManager;
    private boolean canGetLocation = false;
    private Location location;
    private double latitude;
    private double longitude;
    private NewLocationListener newLocationListener;

    public interface NewLocationListener {
        void onLocationChanges(Location location);
    }

    public GPSTracker() {

    }

    @SuppressWarnings("all")
    public Location getLocation() {
        try {
            locationManager = (LocationManager) BaseApplication.getContext().getSystemService(Context.LOCATION_SERVICE);

            // getting GPS status
            boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPSTracker", "Network");
                    if (locationManager != null) {
                        Log.d("GPSTracker", "Network - location manager != null");
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            Log.d("GPSTracker", "Network - last known location != null");
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                            newLocationListener.onLocationChanges(location);
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPSTracker", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            Log.d("LastKnownLocation", "Location: " + locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                                newLocationListener.onLocationChanges(location);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            Log.e(Constants.TAG, e.getMessage(), e);
        }

        return location;
    }

    public static boolean isGpsEnabled() {
        LocationManager locationManager = (LocationManager) BaseApplication.getContext().getSystemService(Context
                .LOCATION_SERVICE);
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    @SuppressWarnings("all")
    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    public void setNewLocationListener(NewLocationListener newLocationListener) {
        this.newLocationListener = newLocationListener;
    }

    public void removeLocationListener() {
        this.newLocationListener = null;
    }

    @SuppressWarnings("InlinedApi")
    public void showSettingsAlert(final Context context) {
        if (alertDialog != null) {
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            alertDialog = new AlertDialog.Builder(context, android.R.style.Theme_Material_Light_Dialog_Alert);
        } else {
            alertDialog = new AlertDialog.Builder(context);
        }
        alertDialog.setTitle(R.string.gps_window_title);
        alertDialog.setMessage(R.string.gps_window_message);

        alertDialog.setPositiveButton(R.string.gps_window_button_positive, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                ((Activity) context).startActivityForResult(intent, LOCATION_SETTINGS_REQUEST_CODE);
            }
        });

        alertDialog.setNegativeButton(R.string.gps_window_button_negative, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        alertDialog.show().setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                alertDialog = null;
            }
        });
    }

    @Override
    public void onLocationChanged(Location location) {
        if (newLocationListener != null) {
            newLocationListener.onLocationChanges(location);
        }
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

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

    public static boolean isGpsStatusChanged() {
        return isGpsStatusChanged;
    }

    public static void setIsGpsStatusChanged(boolean isGpsStatusChanged) {
        GPSTracker.isGpsStatusChanged = isGpsStatusChanged;
    }
}

然后在我的fragment

private void statGPSLocationTracking() {

    Log.d(Constants.TAG, "start gps update");
    // check if GPS enabled
    gpsTracker = new GPSTracker();
    gpsTracker.setNewLocationListener(newLocationListener);
    gpsTracker.getLocation();

    if (!gpsTracker.canGetLocation()) {
        Log.d(Constants.TAG, "GPS not enabled, show enable dialog");
        // stop the gps tracker(removes the location update listeners)
        gpsTracker.stopUsingGPS();

        // ask user to enable location
        gpsTracker.showSettingsAlert(getActivity());
    }
}

private GPSTracker.NewLocationListener newLocationListener = new GPSTracker.NewLocationListener() {
    @Override
    public void onLocationChanges(Location loc) {
        if (getActivity() == null) {
            return;
        }
        // GPS location determined, load the web page and pass the coordinates in the header location section
        Log.d(Constants.TAG, "Location listener onLocationChanges: " + loc);
        infoManager.setCurrentLocation(loc);
        checkRadioInfoNeeded();

        // stop the gps tracker(removes the location update listeners)
        gpsTracker.stopUsingGPS();
    }
};

2 个答案:

答案 0 :(得分:0)

检查

public Location getLocation(){
        try{

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

            // getting GPS status
            boolean isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
           boolean isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            if(!isGPSEnabled && !isNetworkEnabled){

            }else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }

            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return location;

    }

答案 1 :(得分:0)

如果没有此位置权限android.Manifest.permission.ACCESS_FINE_LOCATIONgetLastKnownLocation()将始终返回null。

getLastKnownLocation()不会立即返回位置,需要一些时间。

private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60;

这个

private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
private static final long MIN_TIME_BW_UPDATES = 5 * 1000;

同时删除从网络获取位置的代码。转到Google地图,查看地图是否能够检测到您当前的位置。如果您的地图能够获得位置,那么您的代码也应该获得位置地点断点并查看真正的问题所在。