How does Asynctask actually work?

Asked

Viewed 1,548 times

4

Still, sometimes I get a little confused by the AsyncTask. See 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() {}

}

Confused a little about how the issue of arguments such as AsyncTask<arg1, arg2, arg3>. Here are several questions and mistakes in relation to, but I haven’t noticed anything that actually explains its works or how it should be used. And the doInBackground(String... params)? How does the AsyncTask?

  • There is a very good explanation in Soen here

  • @merchant if you manage to bring to the Sopt, most likely will be rewarded for it =D

  • Lesson 3 of this course explains perfectly everything about Asynctask: https://br.udacity.com/course/android-basics-networking-ud843/

  • 1

2 answers

6

AsyncTask is one of the classes that implements competition in the Android and basically, it helps other classes like: Thread.

Currently, any event or modifying which occurs in a app, is managed in Main Thread of OS. This means that, for example, if you perform a long-term operation on the application, such as downloading a file, it will cause the Main Thread be it stuck until its action is complete. IE, your application will get stuck, the user will not be able to do anything in it, and will only unlock when the file download is completed.

One Asynctask avoids just that. It allows you to create instructions on background and Sincronize these instructions with the Main Thread, that is, the user will be able to continue using the application normally, it will not be locked and you will also be able to update the UI in the course of the process.

Basically, this class doesn’t interfere with Main Thread.

Arguments

The class Asynctask possesses 3 arguments to be implemented, are they:

AsyncTask<ParamsType, ProgressValue, ResultValue> {}
  • Paramstype: Is the guy from parameter which will be sent to the instruction. This parameter will be sent to the method doInBackground().
  • Progressvalue: Like the name says, it’s kind of the value of our progress instruction. It will show the current progress of what we are trying to accomplish.
  • Resultvalue: It’s the kind of final result we’ll get in our instruction. It is the result as a whole. It is returned from the method doInBackground().

Methods

doInBackground()

This method is responsible for two things. The first, it is responsible for receiving the type of parameter you want as a result and the second, it is responsible for the code that will execute our instruction. For example, if we wish to make a Httprequest, this method will be responsible for the code block of the Httprequest and finally, after executing all our code, he will return a value, which is the outworking we wish to see. If we want as a result a String, he will return a String which will be sent to the method onPostExecute.

onPostExecute()

This method is called after the termination of the instructions in the method doInBackground, that is, when everything is complete in the Ackground method, when we have already received the parameter we want to receive, the Onpostexecute method will be called and it will show the result to the user, if you wish. It takes 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();
   }
}

Links Úteis: https://developer.android.com/reference/android/os/AsyncTask.html#onPreExecute()

5

The official documentation is well explained in:

https://developer.android.com/reference/android/os/AsyncTask.html

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

For the 3 parameters (arg1, arg2 and Arg3)

  • arg1 - Data type that will be used as processing input (may have none or may be more than one)

  • arg2 - Data type that will be returned during processing (if necessary. Ex: display processing progress)

  • Arg3 - Data type that will be returned after processing (may not have any).

The Ackground() 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. Parameters are accessed by the param[] array. If you only have one, for example, param[0].

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

The other 2 methods are optional:

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

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

Once all is set, just start the execution. 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);
  • I think it’s cool to also record here that in addition to Asynctask, there are also libraries that work with Jobs in the background, encapsulating some very boring things to do like Scheduling or Retry Strategies, besides making it easier to call Evernote: http://evernote.github.io/android-job/ Job Queue: https://github.com/yigit/android-priority-jobqueue

Browser other questions tagged

You are not signed in. Login or sign up in order to post.