[Advanced] Translation: Bad Asynctask in Android

Source: Internet
Author: User

Asynctask is a very common API, especially for handling data asynchronously and applying data to a view's operations. In fact Asynctask is not so good, even some bad. In this article I will talk about what problems asynctask will cause, how to fix them, and some alternatives to asynctask.

Asynctask

Starting with Android API 3 (1.5 cupcake), Asynctask is introduced to help developers manage threads more easily. In fact, there are similar implementations in Android 1.0 and 1.1, which is usertask. Usertask and Asynctask have the same API and implementations, but because the 1.0 and 1.1 device share is negligible, the concept here does not involve usertask.

Life cycle

There is a widespread misunderstanding about asynctask, and many people believe that a asynctask in activity will be destroyed as the activity is destroyed. And that's not the case. Asynctask will always execute the Doinbackground () method until the method execution finishes. Once the above method is completed, different operations are performed depending on the situation.

    • If Cancel (Boolean) is called, then the oncancelled (Result) method is executed
    • If Cancel (Boolean) is not called, then the OnPostExecute (Result) method is executed

If our asynctask is not canceled when the activity is destroyed, this causes the Asynctask to crash because the view that is processed in the OnPostExecute method no longer exists.

Asynctask's Cancel method requires a Boolean parameter named Mayinterruptifrunning, which means 如果正在执行是否可以打断 that if the value is set to True, the task can be interrupted, or the executing program will continue to execute until it is completed. If there is a looping operation in the Doinbackground () method, we should use iscancelled () in the loop to determine if return is true, we should avoid performing subsequent useless loop operations.

In short, we use asynctask to ensure that Asynctask is properly canceled.

Cancel () A short answer that doesn't work well sometimes works.

If you call Asynctask's Cancel (false), Doinbackground () will still execute to the end of the method, but will not call the OnPostExecute () method. But this is 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 ends early, but if Doinbackground () has a non-disruptive method that is invalidated, such as this bitmapfactory.decodestream () IO operation. But you can close the IO stream early and catch the exception thrown by such an operation. But this will make the cancel () method meaningless.

Memory leaks

Another common case is the use of non-static anonymous internal asynctask classes in the activity, which, due to the characteristics of the Java inner class, holds an implicit reference to the outer class of the asynctask. For details, refer to the "invalid" private modifier of the asynctask, because the life cycle of the asynctask is likely to be longer than the activity, and when the activity is destroyed, it is still executing because asynctask holds the activity reference , causing the activity object to fail to be recycled, resulting in a memory leak.

Results are missing

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

Serial or parallel

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

new AsyncTask1().execute();new AsyncTask2().execute();

Do the two tasks above execute at the same time, or will the 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. The use of multiple asynctask may pose some problems due to serial execution of tasks. So this is not a good way to handle asynchronous operations, especially if you want to work with the results in a UI attempt.

From 1.6 to 2.3 (gingerbread)

Later, the Android team decided to let Asynctask parallel to solve the problem caused by 1.6, this problem is solved, the new problem arises again. Many developers actually rely on the sequential execution behavior. So many concurrent problems flocked.

3.0 (Honeycomb) to present

Well, the developers might not like to have asynctask parallel, so the Android team changed asynctask to serial. Of course, this one 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 had control over the execution, whether it would 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?

Not so, using asynctask although you can implement asynchronous operations with short code, but as mentioned in this article, you need to let Asynctask work properly, you need to pay attention to a lot of rules. One of the recommended techniques for asynchronous operations is to use loaders. This method is introduced from Android 3.0 (Honeycomb) and is included in the Android support package. You can learn more about loaders by viewing the official documentation.

This translation of the original text has a small part of the deletion of modified processing.

[Advanced] Translation: Bad Asynctask in Android

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.