Pro Android with Kotlin


Download 5.42 Mb.
Pdf ko'rish
bet155/223
Sana04.11.2023
Hajmi5.42 Mb.
#1746807
1   ...   151   152   153   154   155   156   157   158   ...   223
Bog'liq
@de android telegram Pro Android with Kotlin Developing Modern Mobile

181
CHAPTER 8: APIs
the online service needs to look up a huge database. An IntentService will do the job for 
us, and from among the methods that can return us the value, we choose a ResultReceiver 
passed by intent extras. First we define kind of a contract between the service and the 
service clients of a class holding some constants.
class GeocoderConstants {
companion object Constants {
val SUCCESS_RESULT = 0
val FAILURE_RESULT = 1
val PACKAGE_NAME = "
"
val RECEIVER = "$PACKAGE_NAME.RECEIVER"
val RESULT_DATA_KEY =
"$PACKAGE_NAME.RESULT_DATA_KEY"
val LOCATION_DATA_EXTRA =
"$PACKAGE_NAME.LOCATION_DATA_EXTRA"
}
}
Now the full service class reads as follows.
class FetchAddressService :
IntentService("FetchAddressService") {
override
fun onHandleIntent(intent: Intent?) {
val geocoder = Geocoder(this, Locale.getDefault())
var errorMessage = ""
// Get the location passed to this service through
// an extra.
val location = intent?.getParcelableExtra(
GeocoderConstants.LOCATION_DATA_EXTRA)
as Location
// Get the Intent result receiver
val receiver = intent.getParcelableExtra(
GeocoderConstants.RECEIVER) as ResultReceiver
var addresses: List
? = null
try {
addresses = geocoder.getFromLocation(
location.getLatitude(),
location.getLongitude(),
1) // Get just a single address!
} catch (e: IOException) {
// Catch network or other I/O problems.
errorMessage = "service_not_available"
Log.e("LOG", errorMessage, e)
} catch (e: IllegalArgumentException) {
// Catch invalid latitude or longitude values.
errorMessage = "invalid_lat_long_used"
Log.e("LOG", errorMessage + ". " +
"Latitude = " + location.getLatitude() +



Download 5.42 Mb.

Do'stlaringiz bilan baham:
1   ...   151   152   153   154   155   156   157   158   ...   223




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling