Open siliconprime-thanhduc opened 5 years ago
thank you for giving me the idea for making it in background service but please note that IntentService is now deprecated and documentation advice using WorkManger you can learn it and perform same task from here here's the full code
class AddressDetailsWorker(var context: Context, workerParams: WorkerParameters) :
Worker(context, workerParams) {
override fun doWork(): Result {
val lang = inputData.getString("lang")
val geoCoder = lang?.let {
Geocoder(applicationContext, Locale(it))
}
val address = geoCoder?.getFromLocation(inputData.getDouble("latitude", 0.0),
inputData.getDouble("longitude", 0.0), 1)
try {
address?.let {
if (address.isNotEmpty()) {
// WorkManger can take only specific parameters
// and not POJO or array list so make sure you send data as a primitive data type
// if you tried to pass something else it'd throw an exception illegalargumentexception
val data = Data.Builder()
.putDataType("key_name", "value")
.build()
return Result.success(data)
}
}
} catch (e: Throwable) {
Timber.e(e)
}
return Result.failure()
}
}
The getFromLocation() method provided by the Geocoder class accepts a latitude and longitude and returns a list of addresses. The method is synchronous and may take a long time to do its work, so you should not call it from the main, user interface (UI) thread of your app.
The IntentService class provides a structure for running a task on a background thread. Using this class, you can handle a long-running operation without affecting your UI's responsiveness.
Define a FetchAddressIntentService class that extends IntentService. This class is your address lookup service. The intent service handles an intent asynchronously on a worker thread and stops itself when it runs out of work. The intent extras provide the data needed by the service, including a Location object for conversion to an address and a ResultReceiver object to handle the results of the address lookup. The service uses a Geocoder to fetch the address for the location and sends the results to the ResultReceiver.
We can see all here : https://developer.android.com/training/location/display-address
and code here https://github.com/jimmy-jose/CurrentLocation