I do wanted achieve the same objective, well now you can achieve that and many other information which will be available in the location object which you may receive in LocationCallback
. I have enabled a Service
for fetching location, so LocationCallback
is placed in my Serivce Class LocationService
For this, you have to call the LocationCallback
object as stated below :
private lateinit var locationCallback: LocationCallback
locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
if (locationResult.lastLocation != null) {
val location = locationResult.lastLocation
val intent = Intent(ACTION_LOCATION_UPDATE)
// Add the current location as an extra to the intent
intent.putExtra(EXTRA_LOCATION, location)
val latitude = locationResult.lastLocation!!.latitude
val longitude = locationResult.lastLocation!!.longitude
Log.d("LAT_LOND","Current Position : $latitude | $longitude")
sendBroadcast(intent)
}
}
}
Now you have to call the callback using FusedLocationProviderClient
private lateinit var fusedLocationClient: FusedLocationProviderClient
// Initialize fusedLocationClient
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
//Calling the locationCallback object
fusedLocationClient.requestLocationUpdates(
LocationUtils.getLocationRequest(),
locationCallback,
null
)
Here, as you can see I have passed the whole object of location in a BroadcastReceiver
because I wanted to display the information into an activity. Attaching the Activity code as well for your reference.
private val receiver = object : BroadcastReceiver() {
@RequiresApi(Build.VERSION_CODES.O)
@SuppressLint("SetTextI18n")
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == LocationService.ACTION_LOCATION_UPDATE) {
val location = intent.getParcelableExtra<Location>(LocationService.EXTRA_LOCATION)
// Updating the UI with the new location data
binding.tvLat.text = location?.latitude.toString().trim()
binding.tvLong.text = location?.longitude.toString().trim()
binding.tvAcc.text = "${location?.accuracy.toString().trim()} meters in horizontal"
binding.tvAccVer.text =
"${location?.verticalAccuracyMeters.toString().trim()} meters in vertical"
binding.tvTime.text = convertLongToTime(location?.time!!)
}
}
}
You can see that the object of locationCallback
holds all the data, from this you can retrieve the information you need.
Also, keep a note in mind that you should enable all the required permissions for fetching location and receiving data of the location.
For better understanding, I am sharing a link where you can enable runtime permissions from the user and interact with the Application, so that the application does not behave improper.
LINK - Runtime Location Permissions Android
Feel free to comment your thoughts on this and do suggest any changes if needed.