The bad asynctask_android in Android

Source: Internet
Author: User
Tags documentation

Asynctask is a very common API, especially when processing data asynchronously and applying the data to the view's operational context. In fact, Asynctask is not so good, even some bad. In this article I'll talk about the issues that asynctask can cause, how to fix them, and some alternatives to asynctask.

Asynctask

Starting with the Android API 3 (1.5 cupcake), Asynctask was introduced to help developers manage threads more simply. In fact, there is a similar implementation in Android 1.0 and 1.1, which is usertask. Usertask and Asynctask have the same APIs and implementations, but because of the negligible share of 1.0 and 1.1 devices, the concept here is not about Usertask.

Life cycle

There is one such widespread misconception about asynctask that many people believe that a asynctask in activity will be destroyed as the activity is destroyed. And that's not the case. Asynctask always executes the Doinbackground () method until the method execution is finished. Once the above method is finished, different actions will be performed depending on the situation.

If Cancel (Boolean) is invoked, the oncancelled (result) method is executed

If Cancel (Boolean) is not invoked, the OnPostExecute (result) method is executed

The Asynctask Cancel method requires a Boolean parameter named Mayinterruptifrunning, which means if the execution can be interrupted, if this value is set to True, the task can be interrupted, otherwise The program you are executing will continue to execute until it is completed. If there is a circular operation in the Doinbackground () method, we should use iscancelled () in the loop to determine that if we return to true, we should avoid performing subsequent useless loops.

In short, we use Asynctask to make sure Asynctask is properly canceled.

Cancel () that doesn't work well

The answer, in short, sometimes works.

If you call Asynctask Cancel (false), Doinbackground () still executes to the end of the method, but does not invoke the OnPostExecute () method. But it's actually a meaningless operation for the application to perform. So is it possible to solve the problem before we call Cancel (true)? Not so. If Mayinterruptifrunning is set to True, the task will end as soon as possible, but if the doinbackground () is not interrupted, such as this bitmapfactory.decodestream () IO operation. But you can close the IO stream ahead of time and catch the exception thrown by this operation. But this makes the cancel () method meaningless.

Memory leaks

Another common scenario is the use of Non-static anonymous internal asynctask classes in the activity, which, because of the characteristics of the Java inner class, holds an implicit reference to the outer class for the Asynctask inner class. For details, please refer to the private modifier for "fail", because the life cycle of the asynctask may be longer than the activity, when the activity is destroyed Asynctask is still executing, because Asynctask holds the reference to the activity , causing the activity object to be recyclable, resulting in a memory leak.

Result lost

Another problem is the problem of asynctask data loss when the activity is recreated, such as screen rotation. When the activity is destroyed and created, the asynctask that is still running will hold an illegal reference to the activity, which is the previous activity instance. Causes OnPostExecute () to have no effect.

Serial or parallel

There are a lot of questions about serial or parallel asynctask, which is normal because it has been modified many times. If you don't understand what serial or parallel is, you can learn from the following example, assuming we have two lines of code in a method body

New AsyncTask1 (). Execute ();
New AsyncTask2 (). Execute ();

Do the two tasks above be executed at the same time, or will AsyncTask2 be executed after the AsyncTask1 execution is completed? The results are actually different depending on the API.

Before 1.6 (Donut):

In the first edition of the Asynctask, the task is serial scheduling. One task execution completes another to execute. Using multiple asynctask may cause problems due to serial execution of tasks. So this is not a good way to handle asynchronous operations, especially if you need to effect the results on UI attempts.

From 1.6 to 2.3 (gingerbread)

Later, the Android team decided to let Asynctask parallel to solve the problem caused by 1.6, the problem is solved, new problems arise. Many developers actually depend on the behavior of sequential execution. So many concurrent problems flocked in.

3.0 (Honeycomb) to the present

Well, developers may not like to have asynctask parallel, so the Android team has changed asynctask to serial. Of course this time the modification does not completely prohibit asynctask parallelism. You can implement multiple Asynctask parallelism by setting Executeonexecutor (Executor). A description of the API documentation is as follows

If we want to make sure we have the execution, whether it'll run serially or parallel, we can check at Runt IME with this code to make sure it runs parallel:

public static void Execute (Asynctask as) {
 if Build.VERSION.SDK_INT <= build.version_codes. HONEYCOMB_MR1) {
   as.execute ();
 } else {
   as.executeonexecutor (asynctask.thread_pool_executor);
 }
}
//(This code does not work for API lvl 1 to 3)

Do you really need a asynctask?

This is not true, although using asynctask can be done asynchronously with short code, but as this article mentions, you need to be aware of a lot of rules and regulations to make asynctask work. One of the recommended techniques for asynchronous operations is to use loaders. This approach is introduced from the Android 3.0 (Honeycomb) and is included in the Android support package. You can learn more about loaders by looking at the official documentation.

This translation of the original text has a small part of the deletion of the modification process.

The above is to the Android Asynctsak data collation, and then continue to supplement the relevant information, thank you for your support of this site!

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.