The fused Location Provider will only maintain background location if at least one client is connected to it. Now just turning on the location service will not guarantee to store the last known location.

Once the first client connects, it will immediately try to get a location. If your activity is the first client to connect and getLastLocation() is invoked right away in onConnected(), that might not be enough time for the first location to arrive..

I suggest you to launch the Maps app first, so that there is at least some confirmed location, and then test your app.

Answer from Amit K. Saha on Stack Overflow
🌐
Medium
medium.com › @debuggingisfun › fusedlocationproviderclients-null-location-2e13d6128031
FusedLocationProviderClient’s null location | by Vairavan Srinivasan | Medium
August 21, 2023 - FusedLocationProviderClient supports getCurrentLocation to fetch available current location. However, it is documented to return a null location if unable to fetch it and to make things worse it invokes the success callback with a null location.
🌐
Google
developers.google.com › google play services › fusedlocationproviderclient
FusedLocationProviderClient | Google Play services | Google for Developers
October 31, 2024 - This may return a cached location if a recent enough location fix exists, or may compute a fresh location. If unable to retrieve a current location fix before timing out, null will be returned.
Top answer
1 of 13
73

The fused Location Provider will only maintain background location if at least one client is connected to it. Now just turning on the location service will not guarantee to store the last known location.

Once the first client connects, it will immediately try to get a location. If your activity is the first client to connect and getLastLocation() is invoked right away in onConnected(), that might not be enough time for the first location to arrive..

I suggest you to launch the Maps app first, so that there is at least some confirmed location, and then test your app.

2 of 13
50

As in this post said, The fused Location Provider will only maintain background location if at least one client is connected to it.

But we can skip the process of launching the Google Maps app to get last location by following way.

What we need to do is

  1. We have to request location update from FusedLocationProviderClient
  2. Then we can get the last location from FusedLocationProviderClient, it wouldn't be null.

Request Location

LocationRequest mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(60000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationCallback mLocationCallback = new LocationCallback() {
    @Override
    public void onLocationResult(LocationResult locationResult) {
        if (locationResult == null) {
            return;
        }
        for (Location location : locationResult.getLocations()) {
            if (location != null) {
                //TODO: UI updates.
            }
        }
    }
};
LocationServices.getFusedLocationProviderClient(context).requestLocationUpdates(mLocationRequest, mLocationCallback, null);

Get last location

LocationServices.getFusedLocationProviderClient(context).getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            //TODO: UI updates.
        }
    });

For best result requestLocationUpdates in onStart() of the Activity, and then you can get last location.

🌐
Medium
medium.com › @stevekamau72 › how-to-fix-null-lastlocation-from-fusedlocationproviderclient-6629280a90b4
How to fix null lastLocation from FusedLocationProviderClient | by Steve Kamau | Medium
January 4, 2024 - private fun getDeviceLocation() { val fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(requireContext()) val locationResult = fusedLocationProviderClient.lastLocation locationResult.addOnCompleteListener(requireActivity()) { task -> if (task.isSuccessful) { // i check for the result here, if null it means the location object is null if (task.result == null) { // so we need to find a different way to force this retrieval handleNewLocation() return@addOnCompleteListener } // do what you want with task.result } else { Timber.tag(TAG).d("Current location is null. Using
🌐
Android Developers
developer.android.com › core areas › sensors and location › get the last known location
Get the last known location | Sensors and location | Android Developers
To avoid this situation you can create a new client and request location updates yourself. For more information, see Request location updates. The FusedLocationProviderClient provides several methods to retrieve device location information.
🌐
Stack Overflow
stackoverflow.com › questions › 72078561 › why-does-fusedlocationproviderclient-getcurrentlocation-always-return-a-null-o
android - Why does FusedLocationProviderClient.getCurrentLocation() always return a null object? - Stack Overflow
I am trying to get the location whenever a user clicks a button. I have the code below but the outcome of "location" always is null. I am running this on an emulator in Android Studio and whenever I check out the app info, location services are turned on and location permission is successfully granted.
🌐
Kotlinlang
slack-chats.kotlinlang.org › t › 470120 › hello-everyone-i-am-currently-having-an-issue-with-fusedloca
Hello everyone i am currently having an issue with FusedLoca kotlinlang #android
as per your suggestion I opened the map app and a popup appeared briefly and afterwards showed my current location. When I went back in the app, the "val test" and "val deviceLocation" correctly retrieved the fusedLocation ... requestLocationUpdates and I'd resume the continuation after the first result (Also you should dispose the listener after the first result) ... @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) @SuppressLint("MissingPermission") fun startLocationUpdate() = fusedLocationProviderClient.requestLocationUpdates( locationRequest, locationCallback, Looper.getMainLooper() ) this is what I call every time from a lifecycle aware service binded to the UI
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 53029418 › fusedlocationprovider-return-null
android - FusedLocationProvider return null - Stack Overflow
and if location null update fused location provider · public void getDeviceLocation() { try { final Task<Location> locationTask = fusedLocationProviderClient.getLastLocation(); locationTask.addOnSuccessListener((Activity) context, new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { if (location != null) { lastKnownLocation = location; if(map==null){ Toast.makeText(context,"map null",Toast.LENGTH_LONG).show(); return; } map.moveCamera(CameraUpdateFactory.newLatLngZoom( new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude()), Constants.
Top answer
1 of 2
14

I found a solution, this is what happens, when the location is null it means the location cache was cleared, this happens when turning off GPS, so when I was turning it on there was no last location to get, what I did was this:

checkLocationSettings(callingActivity, turnOnGpsRequestCode, callback) {
                // Location settings successful
                mFusedLocationProviderClient!!.lastLocation
                        .addOnSuccessListener(callingActivity) {
                            location ->
                            if (location == null || location.accuracy > 100) {
                                mLocationCallback = object : LocationCallback() {
                                    override fun onLocationResult(locationResult: LocationResult?) {
                                        stopLocationUpdates()
                                        if (locationResult != null && locationResult.locations.isNotEmpty()) {
                                            val newLocation = locationResult.locations[0]
                                            callback.onCallback(Status.SUCCESS, newLocation)
                                        } else {
                                            callback.onCallback(Status.ERROR_LOCATION, null)
                                        }
                                    }
                                }

                                mFusedLocationProviderClient!!.requestLocationUpdates(getLocationRequest(),
                                        mLocationCallback, null)
                            } else {
                                callback.onCallback(Status.SUCCESS, location)
                            }
                        }
                        .addOnFailureListener {
                            callback.onCallback(Status.ERROR_UNKNOWN, null)
                        }
            }

When the location is null, start requesting locations using a callback and

mFusedLocationProviderClient!!.requestLocationUpdates(getLocationRequest(), mLocationCallback, null)

Then when the callback is called, a new location is got and it starts getting location again.

Sometimes it happens that when you turn on the GPS, the location is not null but the accuracy is bad, so I also check if location accuracy is good enough (For me good enough is 100 meters)

2 of 2
1

You can use getLocationAvailability() method on your FusedLocationPrivedClient object and if it returns true then only use getLastLocation() method otherwise use requestLocationUpdates() method like this :

FusedLocationProviderClient fusedLocationProviderClient =
            LocationServices.getFusedLocationProviderClient(InitActivity.this);
    if (ActivityCompat.checkSelfPermission(this.getApplicationContext(),
            android.Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {

fusedLocationProviderClient.getLocationAvailability().addOnSuccessListener(new OnSuccessListener<LocationAvailability>() {
                @Override
                public void onSuccess(LocationAvailability locationAvailability) {
                    Log.d(TAG, "onSuccess: locationAvailability.isLocationAvailable " + locationAvailability.isLocationAvailable());
                    if (locationAvailability.isLocationAvailable()) {
                        if (ActivityCompat.checkSelfPermission(InitActivity.this.getApplicationContext(),
                                android.Manifest.permission.ACCESS_FINE_LOCATION)
                                == PackageManager.PERMISSION_GRANTED) {
                            Task<Location> locationTask = fusedLocationProviderClient.getLastLocation();
                            locationTask.addOnCompleteListener(new OnCompleteListener<Location>() {
                                @Override
                                public void onComplete(@NonNull Task<Location> task) {
                                    Location location = task.getResult();                                    
                                }
                            });
                        } else {
                            requestLocationPermissions ();
                        }

                    } else {
fusedLocationProviderClient.requestLocationUpdates(locationRequest, pendingIntent);

                    }

                }
            });
        } else {
            requestLocationPermissions ();
        }
🌐
Stack Overflow
stackoverflow.com › questions › 42209938 › location-is-null-fused-location-provider-android
Location is null Fused location provider android - Stack Overflow
if (isLocationEnabled(getApplicationContext())) { mMenu.getItem(0).setVisible(true); } else { Snackbar.make(mLayout, getString(R.string.loc_not_enable), Snackbar.LENGTH_LONG).show(); } } }); //setup GoogleApiclient buildGoogleApiClient(); public static boolean isLocationEnabled(Context context) { int locationMode = 0; String locationProviders; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){ try { locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE); } catch (SettingNotFoundException e) { e.printStackTrace(); return false; } return locatio
🌐
Medium
droidbyme.medium.com › get-current-location-using-fusedlocationproviderclient-in-android-cb7ebf5ab88e
Get Current location using FusedLocationProviderClient in Android | by Droid By Me | Medium
January 2, 2019 - 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.
🌐
Stack Overflow
stackoverflow.com › questions › 63223410 › does-fusedlocationproviderclient-need-to-initialize-location-often-null
android - Does FusedLocationProviderClient need to initialize? location often null - Stack Overflow
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" /> <!-- I think this is required for Android 10 (API 29) + --> ... class ClassName : AppCompatActivity() { private lateinit var fusedLocationClient: FusedLocationProviderClient private val locationCallBack: LocationCallback = object : LocationCallback() { override fun onLocationResult(p0: LocationResult?) { val location: Location? = p0?.lastLocation if(location != null) { latitude = location.latitude.toString() longitude = location.longitude.toString() } } } override fun onCreate(savedInstanceState: Bundle?)
🌐
Google
developers.google.com › google play services › fusedlocationproviderapi
FusedLocationProviderApi | Google Play services | Google for Developers
When LocationAvailability.isLo... specified by the active LocationRequests. If the client isn't connected to Google Play services and the request times out, null is returned....
🌐
Stack Overflow
stackoverflow.com › questions › tagged › fusedlocationproviderclient
Newest 'fusedlocationproviderclient' Questions - Stack Overflow
I used FusedLocationProviderClient with JobScheduler to get current location all time and it working well when app in background. But getCurrentLocation() method return Location = null when I tested ...
🌐
Akaver
courses.taltech.akaver.com › 13 - fused location
13 - Fused location | Native Mobile Applications - Courses
March 29, 2026 - -> if (location != null) { locationReceive(location) } else { Log.w(TAG, "Initial location was null") } } } @SuppressLint("MissingPermission") private fun locationReceive(location: Location, updateNotification: Boolean = false) { prevLocation?.apply { distance += location.distanceTo(this) } if (updateNotification) { val notification = buildNotification(this, "Foreground Service", "Distance: $distance") NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, notification) } prevLocation = location } @SuppressLint("MissingPermission") private fun requestLocationUpdates() { if (!permissionsG
🌐
Codepath
guides.codepath.org › android › Retrieving-Location-with-LocationServices-API
Retrieving Location with LocationServices API | Android Development | CodePath Guides
public void getLastLocation() { // Get last known recent location using new Google Play Services SDK (v11+) FusedLocationProviderClient locationClient = getFusedLocationProviderClient(this); locationClient.getLastLocation() .addOnSuccessListener(new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { // GPS location can be null if GPS is switched off if (location != null) { onLocationChanged(location); } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.d("MapDemoActivity", "Error trying to get last GPS location"); e.printStackTrace(); } }); }
Top answer
1 of 2
3

Instead of getting the last known location, you can get location updates in specific intervals. Here is the code.

Declare these fused location provider class and location callback class

private var mFusedLocationProviderClient: FusedLocationProviderClient? = null
private var mLocationRequest: LocationRequest? = null
private var mLocationCallback: LocationCallback? = null  
private const val LOCATION_REQUEST_INTERVAL: Long = 5000

`

Here is the necessary method for the location request

private fun createLocationRequest() {
    mLocationRequest = LocationRequest.create()
    mLocationRequest!!.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
    mLocationRequest!!.setInterval(LOCATION_REQUEST_INTERVAL).fastestInterval =
    LOCATION_REQUEST_INTERVAL
    requestLocationUpdate()
}

private fun requestLocationUpdate() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
        != PackageManager.PERMISSION_GRANTED ) {

        Log.e("permission", "denied");


        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return
    }

    mFusedLocationProviderClient!!.requestLocationUpdates(
        mLocationRequest,
        mLocationCallback,
        Looper.myLooper()
    )
}

Then call these "createLocationRequest" method and location callback classs in onCreate().

    mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(requireContext())

 createLocationRequest()
 mLocationCallback = object : LocationCallback() {

        override fun onLocationResult(locationResult: LocationResult) {
            super.onLocationResult(locationResult)
             val lat  = locationResult.lastLocation.latitude
             val lng = locationResult.lastLocation.longitude
                                
     
        }
    }

And remove location update listener in onPause() or onDestory() as per your requirement.

    mFusedLocationProviderClient!!.removeLocationUpdates(mLocationCallback)
2 of 2
0

Scenario 1:After gets message that location is disabled and exits.kill the app from recent app tray now Enable location . Then open App from Home page as new Activity now it should update location. if it's working,nothing wrong in App.App is working properly.

Scenario 2:If you have fusedLocation.getLastLocation() in onCreate() method,move that code to onResume() method.because when you open the App from recent apps tray ,onStart() method will invoked first then onResume() not onCreate().Now enable location ,open the app from recent app tray,check location is updated or not.

   @Override
protected void onResume() {
    super.onResume();
    if (isLocationServiceEnabled) {
        startLocationUpdates();
    }
}