AsyncTask
is one of the classes that implements competition in Android and basically assists other classes like: Thread .
Currently, any event or modification that occurs in an application is managed at Main Thread . This means that, for example, if you perform a long-running operation on the application, such as downloading a file, this will cause Main Thread to be / strong> until your action is complete. That is, your application will get stuck, the user will not be able to do anything in it, and will only unlock when the file is downloaded.
An AsyncTask avoids this. It allows you to create instructions in background and synchronize these instructions with Main Thread , that is, the user will be able to continue using the application normally, it will not be locked and you you can also update the UI in the process.
Basically, this class does not interfere with the Main Thread .
Arguments
The AsyncTask class has 3 arguments to be implemented, these are:
AsyncTask<ParamsType, ProgressValue, ResultValue> {}
-
ParamsType : This is the type of the parameter that will be sent to the statement. This parameter will be sent to the
doInBackground()
method.
-
ProgressValue : As the name says, it is the type of progress value of our statement . It will show the current progress of what we are trying to accomplish.
-
ResultValue : This is the type of final result we will receive in our statement . It is the result as a whole. It is returned from
doInBackground()
method.
Methods
doInBackground ()
This method is responsible for two things. First, it is responsible for receiving the type of parameter you want to have as a result and the second, it is responsible for the code that will execute our statement. For example, if we want to do a HttpRequest , this method will be responsible for the HttpRequest code block, and finally after executing all of our code, it will return a value, which is the result we want to see. If we want as a result a String
, it will return a String
that will be sent to the onPostExecute method.
onPostExecute ()
This method is called after the instructions in the InBackground method, that is, when everything is complete in the InBackground method, when we have already received the parameter we want to receive, the OnPostExecute method is called it will show the result to the user, if in case you wish. It gets the parameter you set in the class.
Example
class MTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... result) {
// Http....
return mHttpResponse;
}
@Override
protected void onPostExecute(String resultValue) {
new Toast.makeText(context, resultValue, Toast.LENGTH_SHORT).show();
}
}
Helpful Links : link