在对话框中启用GPS后,Android位置返回null

yel*_*key 6 java gps android geolocation android-6.0-marshmallow

进入屏幕时,我检查是否打开了GPS,如果没有打开,则显示启用GPS的对话框。当用户单击“是”时,onActivityResult-> GPS已打开,我尝试获取位置,但始终返回null

当我已经打开GPS并进入屏幕时,可以正确检索位置。我已经为此苦苦挣扎了几天,似乎找不到任何资源。

UserLocationUtilities.java

public class UserLocationUtilities implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener{

    GoogleApiClient googleApiClient;
    Activity activity;
    protected static final int REQUEST_CHECK_SETTINGS = 0x1;

    boolean isGPSEnabled = false;
    // flag for network status
    boolean isNetworkEnabled = false;
    // flag for GPS status
    boolean canGetLocation = false;

    protected LocationManager locationManager;
    protected LocationListener locationListener;
    protected Location location;
    protected double latitude,longitude;
    protected boolean gps_enabled,network_enabled;

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1 * 1000 * 60; // 1 minute

    public UserLocationUtilities(Activity activity){
        this.activity = activity;
    }

    public void settingsRequest()
    {
        if(googleApiClient == null){
            googleApiClient = new GoogleApiClient.Builder(activity)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this).build();
            googleApiClient.connect();
        }

        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(30 * 1000);
        locationRequest.setFastestInterval(5 * 1000);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest);
        builder.setAlwaysShow(true); //this is the key ingredient

        PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult result) {
                final Status status = result.getStatus();
                final LocationSettingsStates state = result.getLocationSettingsStates();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        // All location settings are satisfied. The client can initialize location
                        // requests here.

                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        // Location settings are not satisfied. But could be fixed by showing the user
                        // a dialog.
                        try {
                            // Show the dialog by calling startResolutionForResult(),
                            // and check the result in onActivityResult().
                            status.startResolutionForResult(activity, REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e) {
                            // Ignore the error.
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        // Location settings are not satisfied. However, we have no way to fix the
                        // settings so we won't show the dialog.
                        break;
                }
            }
        });
    }

    public Location getLocation() {
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            try {
                locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);

                isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

                if (!isGPSEnabled && !isNetworkEnabled) {
                    // no network provider is enabled
                } else {
                    this.canGetLocation = true;
                    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;
    }

    public boolean isLocationEnabled() {
        int locationMode = 0;
        String locationProviders;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            try {
                locationMode = Settings.Secure.getInt(activity.getApplicationContext().getContentResolver(), Settings.Secure.LOCATION_MODE);

            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
            }

            return locationMode != Settings.Secure.LOCATION_MODE_OFF;

        }else{
            locationProviders = Settings.Secure.getString(activity.getApplicationContext().getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            return !TextUtils.isEmpty(locationProviders);
        }


    }

    @Override
    public void onConnected(Bundle bundle) {


    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    @Override
    public void onLocationChanged(Location location) {

    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}
Run Code Online (Sandbox Code Playgroud)

在用户在“设置”对话框的onActivityResult中选择“是”后,我执行location = userlocationutilities.getLocation();。并始终返回null。如果切换屏幕并返回,则检索到位置。

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
// Check for the integer request code originally supplied to startResolutionForResult().
            case REQUEST_CHECK_SETTINGS:
                switch (resultCode) {
                    case Activity.RESULT_OK: //location settings dialog, user selected YES to enabling location

                        location = userLocationUtilities.getLocation();
                        if(location != null){
                            //location of user FOUND
                            Toast.makeText(getActivity(), "Lat: "+location.getLatitude()+" Long: "+location.getLongitude(), Toast.LENGTH_LONG).show();
                            getRingsNearMeCall();

                        }else{
                            //location of user NOT FOUND
                            Toast.makeText(getActivity(), "null location", Toast.LENGTH_LONG).show();

                        }

                        break;
                    case Activity.RESULT_CANCELED: //location settings dialog, user selected NO to enabling location
                        userLocationUtilities.settingsRequest(); //ask user again with Location Settings Dialog
                        break;
                }
                break;
        }
    }
Run Code Online (Sandbox Code Playgroud)

编辑:我在片段中创建了requestPermission,授予了权限

if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[] { Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION },
                    PERMISSION_ACCESS_FINE_LOCATION);
        }else{
            checkLocationSettingsGetRings();
        }
Run Code Online (Sandbox Code Playgroud)

bla*_*ara 0

LocationSettingsRequest 只是用来进行足够的位置设置,例如您想要接收更准确(HIGH_ACCURACY)的位置,那么您需要启用 GPS。因此,在这种情况下,LocationSettingsRequest 会提示对话框允许 api 更改设置。

按确定后,您可以看到 GPS 已启用。但这并不意味着您已被授予位置请求权限。

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case REQUEST_CHECK_SETTINGS:
            switch (resultCode) {
                case Activity.RESULT_OK:
                // Here means required settings are adequate.
                // We can make location request.
                // But are we granted to use request location updates ?
                break;
            }
            break;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

没关系,但是您正在检查权限,但您从未进行requestPermissions。这是获取 null 的第一个可能原因。

public Location getLocation() {
    if (ContextCompat.checkSelfPermission(activity, 
        Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        ...
    }
    return location;
}
Run Code Online (Sandbox Code Playgroud)

即使您之前已获准提出位置请求

  location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
  location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Run Code Online (Sandbox Code Playgroud)

getLastKnownLocation() 方法可能返回 null,这不是意外行为。这是获取 null 的第二个可能原因

您正在发出位置请求,但全局位置变量从未在 onLocationChanged 回调中分配。

 @Override
public void onLocationChanged(Location location) {
    // global location variable is not assigned ?
    // getLocation() method will return null if getLastKnownLocation()
    // did not return null previously. 
}
Run Code Online (Sandbox Code Playgroud)

这是返回 null 的第三个可能原因。

  • 根据我的研究,似乎因为它正在寻找任何其他应用程序的最后一个已知位置,因为自从启用它以来没有其他应用程序使用它,这就是它返回 null 的原因。我只是不确定如何解决这个问题 (2认同)
  • 嗨,@shiv.s。您找到解决方案了吗?我也遇到了同样的问题。 (2认同)