Skip to content Skip to sidebar Skip to footer

Android Get Location Is Null After Phone Reboot

In my app im getting the phone's location via this function, but when I restart the phone and start the app I get null from this method. Is there something that im missing or doing

Solution 1:

When the phone is rebooted the cached last location is lost so if you didnt open up an app that uses GPS like google maps or something then there will be no last location.

There never has to be a location returned to you, you should always assume it could be null

Solution 2:

in case that fusedLocationClient returned null location then you should get the location by yourself using requestLocationUpdates

    fusedLocationClient.lastLocation.addOnSuccessListener { location: Location? ->
            if (location == null) {
                checkLocationSettingsAndStartLocationUpdates(
                    resolutionForResult
                )
            } else {
                showUserCurrentLocation(location)
            }
        }

first let's define resolutionForResult

private val resolutionForResult =
    registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { activityResult ->
        if (activityResult.resultCode == RESULT_OK)
            locationManger.startLocationUpdates(requestPermissionLauncher)
        else {
            showMessage("we can't determine your location")
        }
    }

then this method

privatefuncheckLocationSettingsAndStartLocationUpdates(
    resolutionForResult: ActivityResultLauncher<IntentSenderRequest>
) {
    val builder = LocationSettingsRequest.Builder()
        .addLocationRequest(locationRequest)
    val client: SettingsClient = LocationServices.getSettingsClient(requireContext)
    val task: Task<LocationSettingsResponse> = client.checkLocationSettings(builder.build())

    task.addOnSuccessListener { _ ->
        startLocationUpdates()
    }

    task.addOnFailureListener { exception ->
        if (exception is ResolvableApiException) {
            // Location settings are not satisfied, but this can be fixed// by showing the user a dialog.try {
                val intentSenderRequest =
                    IntentSenderRequest.Builder(exception.resolution).build()
                resolutionForResult.launch(intentSenderRequest)
            } catch (sendEx: IntentSender.SendIntentException) {
            }
        }
    }
}

then startLocationUpdates where the actual location updates happens

funstartLocationUpdates(
    ) {
        if (ActivityCompat.checkSelfPermission(
                requireContext,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                requireContext,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            requestPermissionLauncher.launch(
                Manifest.permission.ACCESS_FINE_LOCATION
            )
            return
        }
        fusedLocationClient.requestLocationUpdates(
            locationRequest,
            locationCallback,
            Looper.getMainLooper()
        )
    }

here is also the declaration of locationRequest and locationCallback

privateval locationRequest: LocationRequest by lazy {
    LocationRequest.create().apply {
        interval = 10000
        fastestInterval = 5000
        priority = LocationRequest.PRIORITY_HIGH_ACCURACY
    }
}

and

privatevar locationCallback: LocationCallback = object : LocationCallback() {
    overridefunonLocationResult(locationResult: LocationResult?) {
        locationResult ?: returnfor (location in locationResult.locations) {
            if (location != null) {
                //showUserCurrentLocation(location)
                stopLocationUpdates(this)//if you only need the location once then stop the updatesbreak
            }
        }
    }
}

here is stopLocationUpdates method

funstopLocationUpdates(locationCallback: LocationCallback) {
    fusedLocationClient.removeLocationUpdates(locationCallback)
}

also the fusedLocationClient is defined once the user gives the permission or after the check for the permission,

Here is how to check if permission guaranted

funlocationPermissionGranted(): Boolean {
    returnwhen (PackageManager.PERMISSION_GRANTED) {
        ContextCompat.checkSelfPermission(
            requireContext,
            Manifest.permission.ACCESS_FINE_LOCATION
        ) -> {
            fusedLocationClient =
                LocationServices.getFusedLocationProviderClient(requireContext)
            true
        }
        else -> {
            false
        }
    }
}

in case of false then you would need to ask for the permissionfun

requestPermission(requestPermissionLauncher: ActivityResultLauncher<String>) {
        requestPermissionLauncher.launch(
            Manifest.permission.ACCESS_FINE_LOCATION
        )
    }

here is the definition for requestPermissionLauncher

private val requestPermissionLauncher = registerForActivityResult(
    ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
    if (isGranted) {
        fusedLocationClient =
                LocationServices.getFusedLocationProviderClient(requireContext())
    } else {
        showMessage(
            "the application can't show your " +
                    "current location on the map, because you denied the location permission"
        )
    }
}

Post a Comment for "Android Get Location Is Null After Phone Reboot"