Search code examples
androidlocation

Location return null on the phone


I want check my current latitude and longitude. This code is working at the emulator but when i check at phone i have null.(android 10)
The application on the phone has location permission.

    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    fusedLocationClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            if(location!=null){
                MyLong=location.getLongitude();
                MyLat=location.getLatitude();
                test.setText(MyLat+" " +MyLong);
            }
            else{
                test.setText("null");
            }
        }
    });

Solution

  • Based on the official android documentation, there are some situations that the last known location could be null and those are

    • Location is turned off in the device settings. The result could be null even if the last location was previously retrieved because disabling location also clears the cache.
    • The device never recorded its location, which could be the case of a new device or a device that has been restored to factory settings.
    • Google Play services on the device has restarted, and there is no active Fused Location Provider client that has requested location after the services restarted

    In those situations you should request location updates. You could check the example of Google's Codelabs