I am designing an Android weather app using Kotlin. I want to get latitude and longitude of the device in background, then fetch weather data for that.
How can I implement an auto detecting latitude and longitude feature in Kotlin?
I am designing an Android weather app using Kotlin. I want to get latitude and longitude of the device in background, then fetch weather data for that.
How can I implement an auto detecting latitude and longitude feature in Kotlin?
Getting a location is pretty boilerplate. Here's a quick example that uses the last known location.
const val REQUEST_CODE_LOCATION_PERMISSION = 100
fun getLocation(context: Context): Location? {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { requestPermissions(); return null }
val mLocationManager = context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager ?: return null
return mLocationManager.getLastKnownLocation(findProvider(mLocationManager) ?: "")
}
fun requestPermissions() {
ActivityCompat.requestPermissions(activity, arrayOf(ACCESS_FINE_LOCATION), REQUEST_CODE_LOCATION_PERMISSION)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_CODE_LOCATION_PERMISSION) getWeather()
}
fun getWeather() {
getLocation()?.let { fetchWeatherData(it.latitude, it.longitude) }
}