Executing tiny asynchronous tasks quickly in Android under 10 lines
Today, when I was working on a project, so I had a situation where I had to perform a very tiny operation in background in Android. I had lots of ideas such as AsyncTask or Thread or using such powerful framework like RxJava or using new APIs such as JobDispatcher or WorkManager etc. You can read about these options in this good article by Ali Muzaffar.
But my major concern was that my requirement was a very simple and little one. I wanted to get address from the location in form of latitude and longitude. And I wanted to do it in background along with showing ProgressBar and stuff. You can check the below GIF image as the result of what I did.
I had a simple method in Utilities class which performed Geocoding on LatLng object and returned an address in String or null if there’s not valid address.
I had setup GoogleMap.OnCameraIdleListener on a GoogleMap object to get the location of the center marker after dragging the map and called the above getAddressFromLocation() method there to get the address like this.
This was working but this had a small issue. If the address takes time in Geocoding, then the progress bar becomes stuck and screen hands including all the UI. This is because long operation is being on the main thread. And according to Android requirements, it should happen on the Worker or any other thread so that UI and main thread cannot be blocked.
Now, I had to put this line of calling getAddressFromLocation in another Thread or something just to make sure that main thread is not blocked. On a simple google search, I found plenty of ways like in this article. I wanted something simpler.
I liked the way of AsyncTask but I didn’t wanted to make another class extending AsyncTask . So, when I dig deeper, I found that there is a static method AysncTask.execute() which performs small operations in Worked thread without creating any extra classes.
So, after adding that my above code became like this:
As you can see, using this simple AsyncTask.execute()method made this thing very simpler. One more thing to note here is that we cannot perform UI operations like setting text on TextView or hiding ProgressBar in this Worker thread. These can only be performed in Main/UI thread. So, that’s why I have called runOnUiThread() method in the thread.
After compiling and running the app, this was the result.