Android Async Asynctask and handler interview seven questions
Source: Internet
Author: User
<span id="Label3"></p>Ask Questions:<p><p><span style="font-size:18px; color:#000099">1. How is asynchronous handled in android?</span></p></p><p><p><span style="font-size:18px; color:#000099">2. How to use handler and how to avoid the memory leakage caused by handler during use?</span></p></p><p><p><span style="font-size:18px; color:#000099">3, from the source point of view analysis messagequeue,message,handler,looper, The main thread, the relationship between child thread</span></p></p><p><p><span style="font-size:18px; color:#000099">4. What is the difference between handler through SendMessage and post runable objects?</span></p></p><p><p><span style="font-size:18px; color:#000099">5, How to create a message loop for a thread, that is, how to build a looper thread?</span></p></p><p><p><span style="font-size:18px; color:#000099">6. What are the methods in asynctask, how to use them, what methods are executed in the main thread, which methods are executed in the sub-threads, and the parameter relationships in Asynctask</span></p></p><p><p><span style="font-size:18px; color:#000099">7, Asynctask and use of the advantages and disadvantages of handler+thread comparison (difference)</span></p></p><p><p><br></p></p>Solve the Problem:<p><p><span style="font-size:18px; color:#ff0000">Question 1 How is asynchronous handled in android?</span></p></p><p><p>Asynchronous processing in Android can take</p></p><p><p>A:handler+thread</p></p><p><p>B: Asynchronous Task Asynctask</p></p><p><p>C:thread+ Callback</p></p><p><p>D:a+c</p></p><p><p><span style="font-size:18px; color:#ff0000">Question 2 How do I use handler and how can I avoid memory leaks caused by handler during use?</span></p></p><p><p><span style="font-size:18px; color:#ff0000">Question 4 What is the difference between handler through SendMessage and post runable objects</span></p></p><p><p></p></p><pre name="code" class="java">public class Threadhandleractivity extends Activity {private static final int msg_success = 0;//get picture successful identity private static F inal int msg_failure = 1;//get picture failed identity private ImageView mimageview;private Button mbutton;private Thread mthread;private Ha Ndler mhandler; @Overridepublic void onCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.thread_layout); mhandler = new MyHandler (this); Mimageview = (ImageView) Findviewbyid ( R.id.imageview)///display picture Imageviewmbutton = (Button) Findviewbyid (r.id.button); mbutton.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {if (mthread = = Null) {mthread = new Thread (runnable); Mthread.star T ();//thread start} else {toast.maketext (getapplication (), getapplication (). getString (r.string.thread_started), Toast.length_long). Show ();}});} Runnable Runnable = new Runnable () {@Overridepublic void run () {//run () runs in a new thread httpclient HC = new Defaulthttpclient (); HttpGet hg = new HttpGet ("http://csdnimg.cn/www/images/csdnindex_logo.gif ");//get csdn logofinal Bitmap bm;try {httpresponse hr = Hc.execute (hg); BM = Bitmapfactory.decodestream (hr.getentity (). getcontent ());} Catch (Exception e) {mhandler.obtainmessage (msg_failure). sendtotarget ();//get picture failed return;} Mhandler.obtainmessage (msg_success, bm). sendtotarget ();//get picture successful, send msg_success identity and bitmap object to UI thread// Mimageview.setimagebitmap (bm); Error! You cannot manipulate UI elements in a non-ui thread/* * * Another more concise way to send messages to the UI Thread. Mhandler.post (new Runnable () {//actually This Runnable does not create a thread, but instead sends a message * Through the source code can be seen in fact that the Runnable object is converted into a message to join the queue @overridepublic void run () {//run () The Mimageview.setimagebitmap method executes on the UI thread (bm);}); **/}}; /** * @author SS * Problem: How to avoid memory leaks caused by handler * 1, do not use non-static internal classes, inherit handler, either in a separate class file, or use static internal class * Why-----> in java, Non-static inner classes and anonymous inner classes implicitly hold references to their external classes, while static inner classes * Do not hold references to external classes. * If the following method is executed in the thread: mhandler.postdelayed (new Runnable () {Runnable here if the anonymous inner class is not used, but is declared outside, it should also be set to static @Override public void Run () {... }}, 1000 * 60 * 10); External call to finish () destroy activity * If we use non-static myhandler, when our code executes the finish method, the deferred message will be present in the main thread message queue for 10 minutes before it is Processed. When we send a target for this handler message to the Looper processing message queue, actually the message that has been sent already contains a reference to the handler instance, so that looper can be called when processing this message handler# The Handlemessage (message) completes the correct handling of the Message. * But Non-static MyHandler holds a reference to an external threadhandleractivity * so this causes the threadhandleractivity to be unable to recycle, which leads to threadhandleractivity holding a lot of resources * Cannot be recycled, this is what we often call a memory Leak. * */private Static class MyHandler extends Handler {//2, when you need to invoke external activity in a static inner class, we can use a weak reference to handle it. Weakreference<threadhandleractivity> thislayout; MyHandler (threadhandleractivity Layout) {thislayout = new Weakreference<threadhandleractivity> (layout);} public void Handlemessage (Message Msg) {//this method runs final threadhandleractivity thelayout = Thislayout.get () on the UI thread; Thelayout = = Null) {return;} Switch (msg.what) {case MSG_SUCCESS:theLayout.mImageView.setImageBitmap ((Bitmap) msg.obj);// ImageView shows the Logotoast.maketext obtained from the network (thelayout,thelayout.getstring (r.string.get_pic_success), TOAST.LEngth_long). show (); break;case MSG_FAILURE:Toast.makeText (thelayout,thelayout.getstring (r.string.get_pic_failure ), toast.length_long). Show (); break;}}}</pre><p><p></p></p><p><p><span style="font-size:18px; color:#ff0000">Issue 3 Analysis of the relationship between messagequeue,message,handler,looper, main thread, and child thread from the source point of view</span></p></p><p><p></p></p><p><p><span style="font-size:18px; color:#ff0000">Question 5 How to build a message loop for a thread, that is, how to build a looper thread?</span></p></p><p><p></p></p><pre name="code" class="java">public class Looperthreadactivity extends activity{/** * messagequeue,message,handler,looper, main thread, child thread relationship * Messa Gequeue: message queuing, with a maximum of one * * Message Message object per thread * Looper: binds to the current thread, guaranteeing that a thread will only have one Looper instance, while a Looper also has only one * MessageQueue constantly from MESSAG Equeue to fetch the message, give the message the target property corresponding to the handler DispatchMessage * to deal with * * Looper is the manager of Messagequeue. Each MessageQueue can not be separated from the Looper, Looper * object creation is achieved through the prepare Function. Each Looper object is associated with one thread at a Time. The Looper object of the current thread can be obtained by calling * Looper.mylooper (). When you create a looper object, A * MessageQueue object is created at the same time. In addition to the default Looper of the main thread, other threads default to the * without the MessageQueue object, so the message cannot be Accepted. If you need to accept, you define a Looper object (via the prepare function), * so that the thread has its own Looper object and MessageQueue data Structure. Looper from MessageQueue * Remove the message and leave it to Handler's Handlemessage for Processing. When processing is complete, call * message.recycle () to place it into the Message Pool. * */private Final int msg_hello = 0; Private Handler mhandler; @Override public void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.main); New customthRead (). start ();//create new and start Customthread instance Findviewbyid (r.id.send_btn). setonclicklistener (new Onclicklistener () {@Override public void OnClick (View V) {//click interface When sending message String s TR = "hello"; LOG.D ("Test", "mainthread is ready to send msg:" + str); Mhandler.obtainmessage (msg_hello, str). sendtotarget ();//send message to Customthread instance}}); } class Customthread extends Thread {@Override public void run () { The steps to establish a message loop Looper.prepare ();//1, Initialize Looper//handler, will first get Looper instances saved in the current thread,/ /in turn associated with MessageQueue in the Looper instance. Mhandler = new Handler () {//2, Looper object bound Handler to customthread instance public void Handlemessage (Message Msg) { 3. Define a method for handling messages switch (msg.what) {case MSG_HELLO:LOG.D ("Test", "customthread receive msg:" + (String) msg.obj); } } }; Looper.loop ();//4, Start Message loop}}}</pre><p><p></p></p><span style="font-size:18px; color:#ff0000"><span style="font-size:18px; color:#ff0000">Question 6 What are the methods in asynctask, how to use them, which methods are executed on the main thread, which methods are executed in the child threads, and the parameter relationships in Asynctask</span></span><p><p></p></p><p><p>lightweight, Asynchronous Abstract class<br>Defines three generic type params,progress and result, all object types<br>OnPreExecute () start calling this method before the task executes, you can display the progress dialog box Here.<br>Doinbackground (Params ...) This method is executed in the background thread, which usually takes a long time to complete the Task's main Work. You can call publicprogress (Progress ...) during Execution. To update the progress of the Task.<br>Onprogressupdate (Progress ...) This method executes on the main thread and is used to show the progress of the task Execution.<br>OnPostExecute (result) This method is executed on the main thread, and the result of the task execution is returned as a parameter to this method.<br>Oncancelled () When the user calls the Cancel method, the function is called Back.<br></p></p><p><p>Instance must be created in the main thread of the UI<br>The Execute method must be called in the main thread<br>Never call manually<br>OnPreExecute (),<br>OnPostExecute (Result),<br>Doinbackground (Params ...),<br>Onprogressupdate (Progress ...) These several methods<br>An Asynctask instance can only be executed once by execute, or an exception will occur multiple times when execute<br>5 Available threads are configured,<br>Executor (executors.newcachedthreadpool ())<br></p></p><p><p></p></p><pre name="code" class="java">/** * Generates the object of this class, and after calling the Execute method * First executes the Onproexecute method * Next executes the Doinbackgroup method */public class Progressbarasynctask Extends asynctask<integer, Integer, string> {private TextView TextView; Private ProgressBar ProgressBar; Public progressbarasynctask (TextView TextView, ProgressBar ProgressBar) {super (); This.textview = textView; This.progressbar = progressBar; }/** * Here the integer parameter corresponds to the first parameter in Asynctask * Here the string return value corresponds to the third parameter of the Asynctask * The method is not run in the UI thread, primarily for asynchronous operation, all the space in the UI cannot be set and modified in this method * but you can invoke the Publishprogress method to trigger Onprogressupdate to manipulate the UI */@Override Protecte D String doinbackground (Integer ... params) {//integer ... params represents a value of 0 or n Integer type netoperator netoperator = n EW Netoperator (); int i = 0; For (i = ten; i <=; i+=10) {netoperator.operator (); Publishprogress (i); }//this inside params[0] is execute (1000) in the return i + params[0].intvalue () + ""; }/** * Here the string parameter corresponds to the third parameter in Asynctask (that is, The return value of the receiving Doinbackground) * runs after the end of the Doinbackground method execution and runs on the UI thread The UI space can be set */@Override protected void OnPostExecute (String Result) {textview.settext ("asynchronous operation Line End "+ result); }//the method runs in the UI thread and runs within the UI thread to set the UI space @Override protected void OnPreExecute () {textview.se Ttext ("start Executing asynchronous threads"); }/** * Here the Intege parameter corresponds to the second parameter in the Asynctask * in the Doinbackground method, each call to the Publishprogress method will trigger Onprogressupdat E execution * Onprogressupdate is executed in the UI thread, all can operate on UI space */@Override protected void Onprogressupdate (Integer: . Values) {int Vlaue = values[0]; Progressbar.setprogress (vlaue); }}/** * Analog Network time consuming * */class netoperator {public void operator () {try {//hibernate 1 sec Thread.Sleep (1000); } catch (interruptedexception E) { TODO auto-generated Catch block E.printstacktrace (); } } }</pre><pre name="code" class="java"><pre name="code" class="java">public class Asynctaskactivity extends Activity {private Button starttaskbtn; Private ProgressBar ProgressBar; Private TextView progress_info; @Override public void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.asyntask_layout); STARTTASKBTN = (Button) Findviewbyid (r.id.starttaskbtn); ProgressBar = (progressBar) Findviewbyid (r.id.progressbar); Progress_info = (TextView) Findviewbyid (r.id.progress_info); Starttaskbtn.setonclicklistener (new onclicklistener () {@Override public void OnClick (View V) { Progressbarasynctask asynctask = new Progressbarasynctask (progress_info, progressBar); Asynctask.execute (1000); } }); } } </pre></pre><p><p><span style="font-size:18px; color:#ff0000">Issue 7 Asynctask vs. advantages and disadvantages of using Handler+thread (difference)</span></p></p><p><p>When implementing asynchronous processing with thread +handler, when a new thread is created for each time-consuming operation, the performance overhead is large, and if the time-consuming operation takes longer to execute, it is possible to run many threads at the same time and the system will eventually be Overwhelmed. In order to improve performance we use Asynctask to implement asynchronous processing, in fact, its internal thread +handler to implement asynchronous Processing. it's just that it uses the thread pooling technology provided by JDK5, effectively reducing the number of threads created and qualifying the number of simultaneous THREADS. There are also some targeted optimization operations on the Pool.<br></p></p><p><p>ASYNCTASK specifies that the number of threads that can run at the same time is 5, and the total size of the thread pool is 128. That is, when we start 10 tasks, only 5 tasks can be executed immediately, while the other 5 tasks need to wait, when a task is completed, the 6th task will start, and so On. The maximum number of threads in a thread pool is 128, and when we try to add a 129th task, the program Crashes.</p></p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px"><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px"></p></p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px"><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px">So in the 3.0 version of the Asynctask change is quite large, before 3.0 Asynctask can have 5 tasks at the same time, and 3.0 after the Asynctask at the same time only one task is Executed. Why are there fewer tasks that can be executed at the same time after the upgrade? This is because the updated asynctask has become more flexible and is free to configure if you do not want to use the default thread pool</p></p><br><p><p>Asynctask<br>Advantages:<br>1. Simple and fast, only need to handle the business in Doinbackground (), update the UI in the OnPostExecute () method, The code hierarchy is simple<br>2. When the data for the same asynchronous task is particularly large, the benefits of Asynctask this thread pool structure are fully reflected<br>Disadvantages:<br>The 1.AsyncTask class contains a global static thread pool, which is configured with 5 available threads by default, and if more than 5 threads go into the buffer queue to Wait. Buffer queue with up to 128 threads in a<br>2.AsyncTask There may be a large number of new threads consuming system resources and causing the risk of applying FC (force Close)<br>3.AsyncTask is not suitable when dealing with a large number of different asynchronous tasks.</p></p><p><p>Handler<br>Advantages:<br>The handler principle is simply to send a message queue without the resource consumption of new threads, which is relatively simple to handle for the complexity of different small asynchronous tasks.<br>Disadvantages:<br>Relative asynctask is too much code, too bloated, the structure is too complex, the level is not clear<br></p></p><br>Demo:https://github.com/feifei003603/customasynctask.git<br><span style="font-size:18px"><span style="font-size:18px">finally finishing, good sleepy, feel useful small partner to a <span style="color:#ff0000">comment</span> bar, There is nothing wrong place welcome to shoot bricks, Welcome to add! </span></span> <p style="font-size:12px;"><p style="font-size:12px;">Copyright Notice: This article for Bo Master original article, without Bo Master permission not Reproduced.</p></p> <p><p>Android Async Asynctask and handler interview seven questions</p></p></span>
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