android tutorial - AsyncTask from concept to implementation in Android Espresso | Developer android - android app development - android studio - android app developement
AsyncTask is a class that allows running operations in the background, with the results being published on the UI thread. The main purpose is to eliminate all the boilerplate code for starting/running a thread by eliminating the handlers and all the stuff that are needed for manipulating the threads. Also, the purpose of AsyncTask is to have short-time operations on a background thread (a few seconds at most), not long-time operations. Therefore, it is important that AsyncTask not be confused with a generic threading framework. If one needs to do long-time operations then the concurrent package is recommended.
General considerations
AsyncTask is defined by three generic types: Params, Progress and Results. From the moment it is executed, it goes through 4 steps (methods). First is onPreExecute, where someone can define a loading dialog, or some UI message that can notify the user the execution is about to start. Next, doInBackground which is the method that is run on asynchronously on a different thread than the Ui thread. The third method is onProgressUpdate which can also run on the UI thread that can notify the user about the status. The last method called it is onPostExecute it is mainly used for publishing the results.
Below is an example on how to use an AsyncTask, returning a string.
Example 1
Example 2
Here, the AsyncTask is a bit different, the execute method receive a list of data to be analyzed in the background. The return result depends on this check.