Android即使启用也无法获取位置

Posted

技术标签:

【中文标题】Android即使启用也无法获取位置【英文标题】:Android unable to get location even if it is enabled 【发布时间】:2021-08-09 11:41:53 【问题描述】:

我正在使用以下方法来获取用户的当前位置。问题是,如果用户已经启用了 GPS,它可能会起作用。但如果他们没有启用它,我会要求他们启用。他们启用它后,我仍然得到“无法找到位置”。我做错了什么?

checkLocation() 中,我检查用户是否启用了 GPS 或网络提供商;

 private void checkLocation() 
    LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER) && !lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) 
        OnGPS();
     else 
        getLocation(lm);
    

如果没有启用,我会要求他们启用它。这里是方法OnGPS()

 private void OnGPS() 
    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setMessage("Enable GPS");
    builder.setCancelable(true);
    builder.setPositiveButton("Yes", (dialog, which) -> 
        dialog.cancel();
        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));


    );
    builder.setNegativeButton("No", (dialog, which) -> dialog.cancel());
    final AlertDialog alertDialog = builder.create();
    alertDialog.show();

下面是我的getLocation()方法

   private void getLocation(LocationManager lm) 
    if (ActivityCompat.checkSelfPermission(
            context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
            context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
        ActivityCompat.requestPermissions(getActivity(), new String[]Manifest.permission.ACCESS_FINE_LOCATION, 1);
    
    else
    
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest);
        LocationServices.getSettingsClient(getActivity()).checkLocationSettings(builder.build());

        Task<LocationSettingsResponse> result =
                LocationServices.getSettingsClient(getActivity()).checkLocationSettings(builder.build());
        result.addOnCompleteListener(task -> 
            try 
                LocationSettingsResponse response = task.getResult(ApiException.class);
                // All location settings are satisfied. The client can initialize location
                // requests here.
             catch (ApiException exception) 
                switch (exception.getStatusCode()) 
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        // Location settings are not satisfied. But could be fixed by showing the
                        // user a dialog.
                        try 
                            // Cast to a resolvable exception.
                            ResolvableApiException resolvable = (ResolvableApiException) exception;
                            // Show the dialog by calling startResolutionForResult(),
                            // and check the result in onActivityResult().
                            resolvable.startResolutionForResult(
                                    getActivity(),
                                    LocationRequest.PRIORITY_HIGH_ACCURACY);
                         catch (IntentSender.SendIntentException e) 
                            // Ignore the error.
                         catch (ClassCastException e) 
                            // Ignore, should be an impossible 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;
                
            
        );
        Location locationGPS = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (locationGPS == null)
        
            locationGPS = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        
        if (locationGPS != null) 
            double lat = locationGPS.getLatitude();
            double longt = locationGPS.getLongitude();
            myGeofire.setLocation(currentUserID, new GeoLocation(lat, longt), (key, error) -> 
                if (error == null) 
                    Log.e("GEOFIRE","Location saved on server successfully!");

                 else 
                    Log.e("GEOFIRE","There was an error saving the location to GeoFire: " + error);
                
            );
            latitude = String.valueOf(lat);
            longitude = String.valueOf(longt);
            // Toast.makeText(FindFriendsActivity.this, "Lat: " + latitude + " Long: " + longitude, Toast.LENGTH_LONG).show();
            HashMap<String, Object> profileMap = new HashMap<>();
            profileMap.put("lat", latitude);
            profileMap.put("longt", longitude);
            rootRef.child("Users").child(currentUserID).updateChildren(profileMap)
                    .addOnCompleteListener(task ->
                    
                        if (task.isSuccessful()) 
                            Log.d("Location:", latitude + longitude);
                            //Toast.makeText(FindFriendsActivity.this, "Location updated successfully!" , Toast.LENGTH_SHORT).show();
                        
                        else
                            String errorMSG = Objects.requireNonNull(task.getException()).toString();
                            Toast.makeText(context, "Error : " + errorMSG, Toast.LENGTH_SHORT).show();
                        
                    );
        
        else
        

            Toast.makeText(context, "Unable to find location.", Toast.LENGTH_SHORT).show();
        
    

最后是 onActivityResult()onLocationChanged() 方法

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) 
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) 
        case LocationRequest.PRIORITY_HIGH_ACCURACY:
            switch (resultCode) 
                case Activity.RESULT_OK:
                    // All required changes were successfully made
                    Log.i("TAG", "onActivityResult: GPS Enabled by user");
                    checkLocation();
                    break;
                case Activity.RESULT_CANCELED:
                    // The user was asked to change settings, but chose not to
                    Log.i("TAG", "onActivityResult: User rejected GPS request");
                    checkLocation();
                    break;
                default:
                    break;
            
            break;
    


@Override
public void onLocationChanged(@NonNull Location location) 
    latitude = String.valueOf(location.getLatitude());
    longitude = String.valueOf(location.getLongitude());

    checkLocation();

【问题讨论】:

【参考方案1】:

我可以通过添加行来解决它

if (locationGPS == null) 
            LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
            locationGPS = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
        

在我的getLocation() 方法中

Location locationGPS = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if (locationGPS == null)
        
            locationGPS = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        

【讨论】:

以上是关于Android即使启用也无法获取位置的主要内容,如果未能解决你的问题,请参考以下文章

仅从 GPRS 网络提供商 Android 获取位置

为啥此代码无法通过 GPS 获取位置?

Android GPS 无法获取我的位置

为啥Android有时无法获取位置

Android Studio:地理定位不起作用。无法在 Webview 中获取地理位置

手机重启后Android无法获取位置