Necessity and implementation of asynchronous processing in Android
2024.3.9
2017.10.1
Applications that require communication may need asynchronous processing for reasons described below, and are implemented using the AsyncTask class.
Why is asynchronous processing necessary?
Let us consider a case in which the displayed content changes depending on the result of communication within an application.
Reflecting the communication result in the display content means that if processing is executed in the same thread, it will wait until the communication is finished before updating the screen.
In this case, all subsequent processes will wait until the communication is finished, which is not only inefficient but also degrades the user experience.
Implementation
Internal class
Create a class that extends the AsyncTask
class within the class that updates the UI.
private class MyTask extends AsyncTask<Params, Progress, Result> {...}
It is also acceptable to use anonymous functions. In fact, it may be more major to use an anonymous function than to use a top-level class.
AsyncTask<Params, Progress, Result> task = new AsyncTask<Params, Progress, Result>() {...};
Types
Params
: type of variable to enter (array)Progress
: type of variable to record updates (used byonProgressUpdate()
)Result
: type of variable returned bydoInBackground()
.
The unused part is specified by Void
.
Methods
Every class must have a doInBackground()
method, in which the background processing is written.
private class MyTask extends AsyncTask<Params, Progress, Result> {
@Override
protected Result doInBackground(Params... params) {
// do something
return result;
}
@Override
protected void onPostExecute(Result result) {
Log.d(TAG, "mesasge: " + String.valueOf(result));
}
}
Although not required, there are also methods onPreExecute()
, onProgressUpdate()
and onPostExecute()
that are executed before, during and after asynchronous processing.
onProgressUpdate()
is a method for using the execution progress, and onPostExecute()
is a method for receiving and processing the results obtained by doInBackground()
.
Implementation in the main thread
Create an instance and execute it.
MyTask task = new MyTask();
task.execute(arg1, arg2, ...);
After doInBackground()
is executed, it moves to the process in onPostExecute()
and updates the screen back to the main thread.