1

I am trying to return the latitude and longitude of my current location using an emulator. I am getting an error that I need to allow ACCESS_FINE_LOCATION even though this is already in my manifest file. Does anyone know why the following code would not work with that even though it is in my manifest file?

thanks in advance!

There is also a version that I tried using fusedLocationClient, but that doesn't do anything I think that's because my location is not changing.

The goal of this code is to display the current location in terms of latitude and longitude as a toast.

    public void displayCurrentLocation(View view){

        LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        double longitude = location.getLongitude();
        double latitude = location.getLatitude();
        Toast.makeText(getApplicationContext(),"Latitude:" + latitude + " Longitude:" + longitude,Toast.LENGTH_SHORT);

//        fusedLocationClient.getLastLocation()
//                .addOnSuccessListener(this, new OnSuccessListener<Location>() {
//                    @Override
//                    public void onSuccess(Location location) {
//                        double longitude = location.getLongitude();
//                        double latitude = location.getLatitude();
//                        Toast.makeText(getApplicationContext(),"Latitude:" + latitude + " Longitude:" + longitude,Toast.LENGTH_SHORT);
//                        if (location != null) {
//                            // Logic to handle location object
//                        }
//                    }
//                });

    }
hippoman
  • 187
  • 2
  • 10
  • Maybe you did the manifest wrong. See this answer: [How to get Latitude and Longitude of the mobile device in android?](https://stackoverflow.com/a/2227299/5221149) – Andreas Apr 03 '19 at 23:53

1 Answers1

0

If your app needs a dangerous permission, you must check whether you have that permission every time you perform an operation that requires that permission. Beginning with Android 6.0 (API level 23), users can revoke permissions from any app at any time, even if the app targets a lower API level.

See Docs for more informations.

This means that you should ask for your permissions everytime users will use that feature.

Here is an example

if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) ==
    PackageManager.PERMISSION_GRANTED &&
    ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
    PackageManager.PERMISSION_GRANTED) {
    //here you do your code for getting latLng
}
else {
  ActivityCompat.requestPermissions(this, new String[] {
  Manifest.permission.ACCESS_FINE_LOCATION, 
  Manifest.permission.ACCESS_COARSE_LOCATION }, 
  TAG_CODE_PERMISSION_LOCATION);

}

Amine
  • 2,241
  • 2
  • 19
  • 41