Android asynchronous load Asynctask specific explanation

Source: Internet
Author: User

had seen someone say. Think it's very reasonable. Share:

technology is divided into two types of surgery and Tao:

(1) The method of specific work is the technique.

(2) The principle and principle of doing things is Tao.


recent projects have identified a major problem. Results log tracking is asynctask caused. Suppose the asynctask is not well understood. The code is buried in Thunder. At which time the future will explode. First of all, we need to understand why Google invented asynctask,asynctask to solve what problem? Android has a principle--- the principle of single-threaded models:UI operations are not thread-safe and must be run in the UI thread .

so Google is making Asynctask , theasynctask extension thread enhances the ability to interact with the main thread.

Let's say your app doesn't interact with the main thread. Then just use the thread directly.

always remember two rules in a single-threaded model:
1. Do not block the UI thread
2. Make sure to access the Android UI Toolkit only in the UI thread


First of all, the 4 methods of Asynctask rewrite:

(1) Doinbackground ()//running in a background thread

(2) OnPreExecute ()//running in the UI thread

(3) Onprogressupdate () //running in the UI thread

(4) OnPostExecute () //running in the UI thread

Specific of these methods how to use, specific unclear can Google, a lot of colleagues speak good concrete.


to properly use the Asynctask class, here are a few guidelines to follow:
1) The instance of the task must be created in the UI thread
2) The Execute method must be called in the UI thread
3) Do not manually call OnPreExecute (), OnPostExecute (Result), Doinbackground (Params ...), Onprogressupdate (Progress ...) These several methods
4) The task can only be run once, otherwise an exception will occur when multiple calls are made
the parameters of the Doinbackground method and OnPostExecute must correspond, and the two parameters are specified in the generic list of asynctask declarations, and the first is Doinbackground The number of parameters to be affected. The second is the number of parameters that show the progress of the run. The third is the Doinbackground return and the OnPostExecute incoming argument.


The above four points I picked from the net. I think it makes sense to point to the 4th. I have objection: even if multiple calls, it should not be an exception, because the Asynctask class has an externally exposed interface, cancel (true), iscancelled (). These two methods, together with the use of these two methods, control Asynctask to manually exit.

There are examples in this source code class that can be specifically Asynctask.java.

Asynctask must is subclassed to be used. The subclass would override at least * one method ({@link #doInBackground}), and most often would override A * second one ({ @link #onPostExecute}.) </p> * * <p>here is an example of subclassing:</p> * <pre class= "Prettyprint" > * Private Class Dow         Nloadfilestask 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"); *     } * }
This is the demo given in the Asynctask, see
if (iscancelled ()) break;

This is used to infer whether to exit the background thread. If you set Cancel (true), the break jumps out of the loop.

Say 2 more points in this place:

(1) Termination thread It's best not to do it with a break, which is too rough. and the integrity of the code is not guaranteed, and the best way to handle it is in the for loop. The while loop adds its own inferred flag bit, just as asynctask this scheme to handle is the best. It's also Google's way of directing us to how to handle terminating threads.

(2) Some students also feel puzzled, said my code there is no loop, how to add the flag bit, in fact, this is generally the background processing, most of the logic of processing loops. Very little code or more than 10 lines of code is very time-consuming, (of course, the network related to another said, there are downloads related, this has other methods to solve).

Even if there is, for example, calling the Jni,so library, returning is slow. This is followed by a number of time-consuming methods with a marker-bit inference.

Through the above method can make a complete design, you can design, when the next time to run Asynctask. First infer if you are running. Assume that it is running. Do not run or cancel the task to run again, this depends on the specific requirements is what;

Give me a chestnut:

private void stopaynctaskrunning () {if (Mcontactslistloader! = null&& Mcontactslistloader.getstatus () = = AsyncTask.Status.RUNNING) {Mcontactslistloader.cancel (true);//if task is still RUNNING, stop it;}}

private void Getcontactslist () {stopaynctaskrunning (); mcontactslistloader = new Contactslistloader (); Mcontactslistloader.executeonexecutor (asynctask.thead_pool_executor);}
Of course, my requirement is to cancel the last task and refresh the data again the next time you come in. Also do not forget to add in the loop statement in Doinbackground ()
@Overrideprotected Integer doinbackground (Object ... arg0) {list<contact> contacts = new arraylist<contact> (); Contentresolver CR = Mcontext.getcontentresolver (); Cursor C = cr.query (contactscontract.contacts.content_uri,projection_contact, NULL, NULL, NULL), if (c! = null) { C.movetoposition ( -1); while (C.movetonext ()) {if (iscancelled ()) {break;}.

。。

。。 }

In this way, the logic according to demand to write, what the demand is like, the logic of the corresponding how to deal with;


Then say Asynctask deceptive place, is in Android3.0 after the version number. The Asynctask is divided into 2 operating methods:

(1) Execute ()
(2) Executeonexecutor ()

Assuming that the Asynctask call (1), the serial running thread, assuming that there are 4 fragment in the activity, and each fragment has a asynctask, this word with (1), it must be run sequentially, and so on, The second one runs. Assuming a method (2), it is possible to run serially. This UI works very well. The thread pool can be used by the system. We can also use a thread pool of our own definition;

Also some descriptions of the number of threads running in the system default thread pool, such as the following:

The following 5 represents the length of the blocked queue for corepoolsize,10. 128 on behalf of Maximumpoolsize
1: Assuming that the number of thread pools is less than 5, create a new thread and run
2: Assume that the number of threads is greater than 5 and less than 5+10 (clogging the queue size). The 6th to 15th thread is added to the blocking queue, and the thread that is blocking the queue is run after the 5 running threads in the thread pool have some end.
3: Assuming that the number of threads is 16~128, the number of threads running is num-10
4: Discard if the number of threads is greater than 128.

The specific introduction can participate in the blog : Android Combat skills: in-depth analysis of Asynctask, This commentary is very specific;

The last thing to note is that the data is loaded in part to refresh the UI, giving the user a good user experience. Give me a chestnut,

private static final int display_num = 10;private list<contact> mcontacts = new arraylist<contact> ();p rivate C Lass Contactslistloader Extendsasynctask<object, Integer, integer> {int count = 0; list<contact> mtempcontacts = new Arraylist<contact> (display_num), @Overrideprotected void OnPreExecute () {Super.onpreexecute (); Mtempcontacts.clear (); Mcontacts.clear ();} @Overrideprotected Integer doinbackground (Object ... arg0) {list<contact> contacts = new arraylist<contact> (); if (c! = null) {c.movetoposition ( -1); while (C.movetonext ()) {if (iscancelled ()) {break;} Contacts.add (Contact), Mtempcontacts.add (Contact), if (++count >= display_num) {publishprogress (); count = 0;}}} return Contacts.size ();} @Overrideprotected void Onprogressupdate (Integer ... values) {super.onprogressupdate (values); Mcontacts.addall ( mtempcontacts); Mtempcontacts.clear (); madapter.notifydatasetchanged ();} @Overrideprotected void OnPostExecute (Integer size) {if (iscancelled ()) return;iF (Size > 0) {if (Mtempcontacts.size () > 0&& mtempcontacts.size ()! = Display_num) {Mcontacts.addall (Mtempco ntacts);}} else {if (mtempcontacts.size () > 0) {mcontacts.addall (mtempcontacts);}} Madapter.notifydatasetchanged ();}}
This is my model, you can understand. will be able to set up their own code to go. This is the logic that I used to dynamically load refresh the UI, refresh the 10 data to refresh once, so as to avoid the impact of the second refresh efficiency, but also to ensure that users do not have to wait until the data is loaded into the talent to see the data. Double Benefit

To learn about many other asynctask, you can refer to the source code. Suppose someone knows more in-depth, welcome children's shoes make brick message;

Android asynchronous load Asynctask specific explanation

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.