Android Asynchronous Task Asynctask detailed _android

Source: Internet
Author: User
Tags ticket

Asynctask, as the name suggests, asynchronous tasks. When it comes to asynchrony, the simplest understanding is a different step. A little more complicated to understand, you have to give an example.

Suppose I am going to the railway station to buy a ticket, just arrived at the railway station I suddenly found I forgot to bring my ID card. What to do? What to do!

Find a way, find a way! I think I should find a classmate in the school to help me send over, because I can not go back to get ah, but also to line up, can not go away. Well, we need someone to send it over. But the problem, I have to send someone ID card, I went to line up, if the first place in the ID card has not yet to do? Ding, the head suddenly lit a small light bulb, witty I in the queue before thinking of two scenarios:

The first scheme, let the conductor waiting for me, I am behind the queue of people waiting for me, I have been in the window of the first place waiting for students to send ID card, until, my ID card was sent, and then a smooth ticket.

Another option is for me to talk to the conductor and let me wait for the ID card to be sent. After the people continue to buy tickets, when my ID card sent to the conductor, I will be able to line up as soon as possible (not necessarily immediately to the first place, because if someone is buying tickets, I can not go to interrupt him) and then buy a ticket.

So, choose the first one or the second? I definitely choose the second, because the choice of the first one will certainly be behind the queue to scold death, but also may be the conductor scolded, do not get beaten, after all, because I a person, wasted so many people's time, also slowed the conductor's work efficiency.

Well, here's the example. In the example, the second method is asynchronous. Asynchrony is often related to multithreading, and asynchronous tasks are mostly done by a single thread, and then return the result to the main thread. Here the conductor is equivalent to CPU, and the person in line to buy the ticket is equal to waiting for the task to be carried out, and I am a task marked as asynchronous (because I know I have an ID card, I can't buy the ticket immediately, so I think of the second option before I line up), when the CPU executes to my task, I found that this task can be performed on the condition (ID) does not have, so I initiated an asynchronous task (classmate send tickets), to obtain the executable conditions, immediately after the position to let out, so that other queued tasks continue to execute. Until I get my ID card, and immediately notify the CPU ready to receive me.

Well, that's pretty much it. Start with the text, Android inside the Asynctask. First on the official website of the quote:

Copy Code code as follows:

Asynctask enables proper and easy to use the UI thread. This class allows to perform background operations and publish results on the UI thread without has to manipulate threa DS and/or handlers.

Is English, although I can understand what the meaning, but still do not translate, afraid of fraught, and so I learn English better again to translate it. However, explain the general meaning, that is, asynctask can do some background operation on the UI thread, but also can return the result of the operation to the UI thread. We know that UI threads can't do time-consuming operations, but with Asynctask we can do so. But

Copy Code code as follows:

Asynctask is designed to being a helper class around Thread and Handler and does not constitute a generic threading framework . Asynctasks should ideally is used for short operations (a few seconds at the most.) If you are need to keep threads running for long periods of time, it is highly your use the recommended APIs various B Y the Java.util.concurrent package such as Executor, Threadpoolexecutor and Futuretask.

For time-consuming tasks, it is not recommended to be executed in Asynctask. Aysnctask is designed as a thread and handler helper class, and cannot perform overly complex and time-consuming tasks, which should be done in other ways. Asynctask is best for operations that take up to a few seconds at most, such as requesting a network operation like XML or JSON to the network, or using the initialization interface of the program, and so on.

The following is the use of asynctask. It's actually very simple.

First you need to define a asynctask subclass, and you must override the Doinbackground (Params ...) of the parent class. Method. There are also OnPostExecute (result) methods that can be rewritten, and this method is automatically invoked after Doinbackground, so you can write some notification code for the task completion here.

Give an official example first:

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) *);
      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");
  }
 

When performing Asynctask, the following statement must be executed in the UI thread.

New Downloadfilestask (). Execute (URL1, URL2, URL3);

As you can see, when inheriting asynctask, there are several generic types, such as Asynctask<url, Integer, and Long>, which are simply explained.

The first can specify the type of the input parameter, which is the parameter of the new Downloadfilestask (). Execute () (finally to Doinbackground), where the argument can be more than one, because the last thing you receive in the method is the array of numbers.
The second specifies the type that is required to send progress updates, typically integers, used in publishprogress (methods used to send progress in the background process, directly, without definition) and onprogressupdate two methods.
The third is the data type of the Asynctask return result, which sets the return type of the doinbackground and the input parameter type of the OnPostExecute
Of course, if you don't need anything, you can use void.

Private class MyTask extends Asynctask<void, Void, void> {...}

In addition, there is a method that can be rewritten, is OnPreExecute (), it is called before Doinbackground, so you can rewrite it and do some work like instantiating the progress bar if needed.

Finally, summarize:

With Asynctask, all you have to do is inherit the parent class and rewrite the Doinbackground (Params ...) to implement background operations in it, rewrite onpostexecute (result) and then handle the results of the background program if there is a return.

If you need to update your progress, instantiate the progress bar (or not here) in OnPreExecute (), and then in Doinbackground (Params ...) The inside uses publishprogress () to publish the progress value, and then rewrite Onprogressupdate (Progress ...) Receives the results of the OnPreExecute () publication and adds code to update the progress bar.

The above is about the asynchronous task of Android content, I hope you can enjoy.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.