How does AsyncTask really work?

3

Still, sometimes I get a bit confused with AsyncTask . Here's an example below:

private class MyAsyncTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {            
        return "Jon Snow";
    }

    @Override
    protected void onPostExecute(String result) {}

    @Override
    protected void onPreExecute() {}

}

A bit confused as to how the argument should be handled as AsyncTask<arg1, arg2, arg3> . Here are several questions and errors in relation, but I did not realize anything that in fact explains its functions or how it should be used. What about doInBackground(String... params) ? How does AsyncTask actually work?

    
asked by anonymous 21.06.2017 / 17:44

2 answers

4

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

    
21.06.2017 / 18:38
4

The official documentation is well explained in:

link

But basically, AsyncTask is made to run background tasks so as not to burden the performance of the main thread or user interface or even to lock it. Examples of background processing: downloading data from the internet, decoding images, etc.

As for the 3 parameters (arg1, arg2 and arg3)

  • arg1 - The type of data that will be used as processing input (may not have any or may be more than one)

  • arg2 - The type of data that will be returned during processing (if necessary, eg display processing progress)

  • arg3 - The data type that will be returned after processing (may not have any).

The InBackground () method is where you define what will be processed in the background and need to receive parameters of the same type defined in arg1 and return a value of the same type defined in arg3. The parameters are accessed by the array param []. If you only have one, for example, it will be param [0].

The onPostExecute () method takes the value returned by the above method (which is the "result" argument) and passes it to the main thread (UI), so you can display a message with the data, set a TextView, image processing, etc.

The other 2 methods are optional:

  • onPreExecute () - If you want to do something before processing begins

  • onProgressUpdate () - returns an intermediate value for the UI of the same type defined in arg2. Optional. Ex: progress status.

Once everything is set, just start running. Ex:

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

DownloadFilesTask task = new DownloadFilesTask();
task.execute(url1, url2, url3);
    
21.06.2017 / 18:28