Recent projects found a major problem, the results of log tracking is asynctask caused. If you don't know enough about Asynctask, the code is to bury the 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 executed in the UI thread .
< Span style= "font-family: Microsoft Jas Black, Verdana, Sans-serif, song body; line-height:22px; " > always remember two rules in a single-threaded model:
1. Do not block the UI thread
2. Ensure that the Android UI Toolkit is accessible 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
Detailed these several methods how to use, concrete unclear can Google, a lot of colleagues speak good detail;
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 executed once, otherwise an exception will occur when multiple calls are made
the parameters of the Doinbackground method and the OnPostExecute must correspond, both of which are specified in the generic parameter list of the Asynctask declaration, and the first is a doinbackground connection Parameters, the second is the parameter that shows the progress, and the third is Doinbackground returns and onpostexecute the arguments passed in.
The above four points is I picked from the net, I think there is a reason, against the 4th, I have objection: even if multiple calls, also should not appear exception, because the Asynctask class has an external interface, cancel (true), iscancelled (). These two methods, together with the use of these two methods, control asynctask can be manually exited. Specific can refer to Asynctask.java this source code class has examples.
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 determine whether to exit the background thread, and if Cancel is set (true), break jumps out of the loop. Say 2 more points in this place:
(1) The termination of the thread is best not to do with the disconnection process, this way is too rough, and can not guarantee the integrity of the code, the best way to do is in the For loop, while the loop to add their own judgment flag, like Asynctask This method to deal with is the best, It's also Google's way of directing us to how to handle terminating threads.
(2) There are students are puzzled, said my code there is no loop, how to add the flag bit, in fact, this is generally the background processing, most of them are processing the logic of the cycle, rarely say a line of code or more than 10 lines of code is time-consuming, (of course, the network related to another said, and download related, this has other methods Even if there are, such as calling the Jni,so library, the return is slow. That is, after a few time-consuming methods to add the mark-bit judgment;
Through the above method can make a complete program design, can design, when the next time to execute Asynctask, first to determine whether they are running, if running, do not execute or cancel the task re-execution, 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 that the next time you come in, cancel the last task and refresh the data again. Also do not forget to include 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 requirements are like, the logic of the corresponding how to deal with;
Again say Asynctask deceptive place, is in Android3.0 later version, Asynctask's execution method is divided into 2:
(1) Execute ()
(2) Executeonexecutor ()
If the Asynctask call (1), the serial execution thread, if there are 4 fragment in the activity, and each fragment has a asynctask, so that in (1), it must be executed sequentially, and so on, a complete execution, The second one is executed. If you use Method (2), it can be executed serially, this UI effect is very good. The thread pool can be used in a system or in our custom thread pool;
In addition, some descriptions of the number of threads executing in the system default thread pool are as follows:
The following 5 represents corepoolsize,10 for the length of the blocking queue, and 128 for Maximumpoolsize
1: If the number of thread pools is less than 5, create a new thread and execute
2: If the number of threads is greater than 5 and less than 5+10 (blocking queue size), the 6th to 15th thread is added to the blocking queue, and the thread executing the blocking queue is removed after the 5 running threads in the thread pool have some end.
3: If 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 detailed introduction can refer to the blog : Android Combat skills: in-depth analysis of Asynctask, This explanation is very detailed;
The last thing to show is that the data to load a part of the UI refresh, give users a good user experience; 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, we understand, you can set up their own code to go. This is the logic that I use to dynamically load the refreshed UI, refresh 10 data and refresh it once, so that you can avoid the effect of the secondary refresh and ensure that users don't have to wait until the data is loaded to see the data. Double Benefit
If you want to know more asynctask, you can only refer to the source code.
Android Asynchronous Load Asynctask detailed