1

I'm trying to get a user's last known location with Android. I can do it using fused locations, but I'm trying to make a simple method to return a user's latitude and longitude location.

Here is what I've tried:

    public static double[] getLocation (Context c) {
        final double[] returnLocation = {0, 0};
        FusedLocationProviderClient fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(c);
        if (c.getApplicationContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            fusedLocationProviderClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    if (location != null) {
                        returnLocation[0] = location.getLatitude();
                        returnLocation[1] = location.getLongitude();
                    }
                }
            });
        }
        return returnLocation;
    }

However, I'm afraid that this is asynchronious, so it returns without actually getting the location.

I appreciate the help.

a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
Jack
  • 57
  • 7
  • By definition, what you want is not possible. You could try getting the last known location, though this may be `null`. Otherwise, you need to take into account that determining the location may take time. In some cases, it may not succeed (e.g., the phone is inside a large building). That is why the APIs for finding the location are asynchronous. – CommonsWare Feb 21 '21 at 22:42

2 Answers2

0

getLastLocation is used to obtain the location information in the cache,and If no cache information is available, null is returned.

zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
0

You can do something like this, I will trigger this method every 2 seconds, until I get the last location.

private void setFusedLocationProviderClient() {
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        final Task<Location> locationResult = fusedLocationProviderClient.getLastLocation();
        locationResult.addOnCompleteListener(this, task -> {
            if (task.isSuccessful()) {
                // Set the map's camera position to the current location of the device.
                if (task.getResult() != null) {
                    //Success
                } else {
                    //Create delay
                    CreateDelay(2000, this::setFusedLocationProviderClient);
                }
            }
        });
    }
Ticherhaz FreePalestine
  • 2,738
  • 4
  • 20
  • 46