【问题标题】:getLastKnownLocation sometimes returns nullgetLastKnownLocation 有时返回 null
【发布时间】:2017-07-18 12:31:29
【问题描述】:

首先让我承认,当您搜索这个特定问题时,会有很多结果。然而,根据这些答案,我尝试过的任何方法都不起作用。有时我得到位置,有时我没有。如果我使用Location 启用/禁用我在调用getLastKnownLocation 时总是得到null。如果我有时手动撤销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();
    }
};

【问题讨论】:

标签: android location android-gps


【解决方案1】:

如果没有此位置权限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;

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

【讨论】:

  • 我试过了,还是不行。我到了if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);locationnull
  • @JackW5808 你能在其他设备上尝试相同的代码并告诉我们结果吗? 2. 另外您能告诉我们您的设备名称吗?
  • 模拟器 Nexus 5X 和华为 P8 都试过了。我现在将在另一台设备上进行测试。
  • 在真实设备上而非模拟器上进行人工测试。
  • 真实设备为Huawei P8
【解决方案2】:

检查一下

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;

    }

【讨论】:

  • 还是null
  • 设备是否有定位权限?
  • 并确保您的设备正在存储最后一个已知位置。如果不去谷歌地图,用 GPS 精确定位我的位置。
  • 是的,位置权限已授予,GPS 也已开启。当我打开 Google Maps 时,我可以看到我的位置,但在我的应用程序中,位置仍然是 null
  • 我没有注意到。但同样的代码对我有用
猜你喜欢
  • 2013-11-06
  • 2013-12-24
  • 2012-05-28
  • 1970-01-01
  • 2015-08-20
  • 1970-01-01
相关资源
最近更新 更多