<span id="Label3"></p><p><p>(1) main thread and ANR</p></p><p><p>Main Thread: UI thread, the interface can be modified only in the main thread, other threads to modify the interface will cause an Exception. This solves the problem of multi-threaded competing UI Resources.</p></p><p><p>Once the code of the main thread is blocked, the interface will not respond, and this behavior is Application. Respond (ANR), the application loses its response.</p></p><p><p>If an event action in the main thread is not responding for more than 5 seconds, Android may pop up a dialog box that the application is not responding to. Activity may be Killed.</p></p><p><p>The following example illustrates Anr,demo as follows, and this time the button loses its response.</p></p><pre class="brush:java;gutter:true;"><pre class="brush:java;gutter:true;">Private Button btn; @Overrideprotected void onCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); btn= (Button) findviewbyid (r.id.button1); btn.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View v) {try {///main thread time-consuming operation Thread.Sleep (10*1000);} catch ( Interruptedexception E) {e.printstacktrace ();}});}</pre></pre><p><p>The cause and avoidance of anr: 1, time-consuming operations are unavoidable, such as network connectivity and network data acquisition, memory read and write, a large number of data calculations, any kind of operation may occupy time, such as network instability, the disk is busy, the CPU is Occupied. 2,ui threads are responsible for monitoring and plotting events, so it is important to ensure that the UI thread is able to respond to the User's needs at any time, that any blocking of the UI thread will affect the User's experience or cause the action in the Anr,ui thread to be as short as Possible. Time-consuming operations (network connection data access, etc.) are done in a separate thread.</p></p><p><p>(2) Android Messaging mechanism, due to the inevitable time-consuming operation of android, the main thread block will affect the interaction with the user, need a mechanism to notify the main thread update interface, this is the message mechanism, looper message mechanism (the main thread view of the message mechanism, message queuing, The Looper loop reads the message, makes a callback for the message, and handler the message mechanism (a programmatic view of the message mechanism). Is the diagram of Looper and handler handling the message Mechanism.</p></p><p><p></p></p><p><p>The operation of the message queue can only be done through handler, when the handler SendMessage method sends a message, the main thread looper will find the message queue changes, and respond to the message, the message will be processed and removed from the team, Processing the response message is also handled by handler, the Handlemessage method. This method is run in the main thread. The method that is commonly used in handler, the void Handlemessage () method, is processed by this method after the message is sent, and this method needs to be Rewritten. The Boolean sendemptymessage (int) method, which sends only a message of what Value. A Boolean sendmesssage (message Message) sends a message to handler, processes the message in handler, sendmessagedelayed (message msg, Long s), Removemessages (int) Deletes the message/canceled message.</p></p><p><p>Here is a demo to illustrate the use of handler and message, the demo is as follows</p></p><pre class="brush:java;gutter:true;">Package Com.example.handlerdemo;import Android.app.activity;import Android.os.bundle;import android.os.Handler; Import Android.os.message;import android.view.view;import Android.widget.button;import android.widget.TextView; public class Mainactivity extends Activity {private static final int message_ok=1;private static final int message_cancle= 2;private static final int message_arg1=3;private static final int message_arg2=4;private Handler handler=new Handler () {p ublic void Handlemessage (android.os.Message msg) {switch (msg.what) {case MESSAGE_OK:txt.setText ("ok"); break;case Message_cancle:if (msg.arg1==message_arg1) {txt.settext ("cancle" + "by user");} Else{txt.settext ("cancle" + "by system");} break;default:break;};}; Private button Btn_ok;private button btn_cancle;private TextView txt;private button btn; @Overrideprotected void onCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); setcontentview (r.layout.activity_main); btn_cancle= (Button) findViewById ( r.id.btn_cancle); btn_ok= (BUtton) Findviewbyid (r.id.btn_ok), btn= (Button) findviewbyid (r.id.btn), txt= (TextView) Findviewbyid (r.id.txt); btn_ Ok.setonclicklistener (new view.onclicklistener () {@Overridepublic void OnClick (View v) {/*message msg=message.obtain ( )///get the formal method of MESSAGE instance msg.what=message_ok;handler.sendmessage (msg); handler.sendemptymessage (message_ok); */// Sendemptymessage method handler.sendemptymessagedelayed (message_ok, 10000);//delay to send the message, there is a way to send the message periodically}}); btn_ Cancle.setonclicklistener (new view.onclicklistener () {@Overridepublic void OnClick (View v) {Message msg= Message.obtain (); msg.what=message_cancle;msg.arg1=message_arg1;//message Parameters. Handler.sendmessage (msg);}}); Btn.setonclicklistener (new view.onclicklistener () {@Overridepublic void OnClick (View v) {handler.removemessages ( Message_ok);//cancel Send message}});}}</pre><p><p>When using the message and looper, we also need to pay attention to the Points: 1,looper and MessageQueue are created when the main thread is created, new threads will not be created by default, in general we will not go direct visitors two Objects. 2,handler must be instantiated with a looper instance, which cannot be instantiated by default in a newly created thread, or an error will Occur. 3, child threads are not instantiated by default for Looper and MessageQueue Objects.</p></p><p><p>(3) the SendMessage () method of thread and Handler,handler can be run in other threads, so we are able to solve the time-consuming problem through the combination of thread and handler. We use a demo that dynamically displays the progress bar control to illustrate the effects such as</p></p><p><p></p></p><p><p>The code is as Follows:</p></p><pre class="brush:java;gutter:true;">Package Com.example.handlerandthreaddemo;import Android.app.activity;import Android.os.bundle;import Android.os.handler;import Android.os.message;import Android.view.view;import Android.widget.button;import Android.widget.progressbar;import Android.widget.textview;public class Mainactivity extends Activity {private Button Btnstart;private TextView tvdownload;private ProgressBar pbdownload;private static final int message_number=1;private int i=0;private Handler handler=new Handler () {public void handlemessage (android.os.Message msg) {if (msg.what==message_ Number) {pbdownload.setprogress (i); tvdownload.settext ("download progress" +i+ "%");};}; @Overrideprotected void onCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( r.layout.activity_main); btnstart= (Button) Findviewbyid (r.id.btnstart); tvdownload= (TextView) Findviewbyid ( R.id.txtdownload);p bdownload= (ProgressBar) Findviewbyid (r.id.pbdownload); btnstart.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnCLick (View v) {new Thread () {public void run () {while (i<100) {try {sleep]; i++; Message msg=message.obtain (); msg.what=message_number;handler.sendmessage (msg);} Catch (interruptedexception e) {e.printstacktrace ();}}};}. Start ();}});}}</pre><p><p>(4) asynchronous communication between Asynctask THREADS.</p></p><p><p>Asynctask is also an asynchronous loading mechanism, note the time when Using: 1,task instance must be created in the main thread, 2,execute () method must be called in the main thread, 3, do not call OnPreExecute (), doinbackground () , Onprogressupdate (), OnPostExecute () and other METHODS. 4, the instantiated task can only be executed once, and repeated calls can occur unexpectedly.</p></p><p><p>Asynctask several common methods: OnPreExecute () method, which is called by the main thread before executing the actual background, the Doinbackground () method is to perform time-consuming operations, execute in the background process, is an abstract method, subclasses must be rewritten, In this method, the Publishprogress () method is called to implement real-time with the new task, and the Onprogressupdate () method is called by the UI thread after the Publisprogress () method is Called. The OnPostExecute () method is done later with the new interface after the background operation is Completed. Here is an example and a description</p></p><p><p></p></p><p><p>Code</p></p><pre class="brush:java;gutter:true;">Package Com.example.asynctask;import Android.app.activity;import Android.os.asynctask;import android.os.Bundle; Import Android.view.view;import Android.widget.button;import Android.widget.textview;public class MainActivity Extends Activity {private Button btnstart,btn;private TextView tv; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); setcontentview (r.layout.activity_main); btn= (Button) Findviewbyid (r.id.button2); btnstart= (Button) findviewbyid (r.id.button1); tv= (TextView) Findviewbyid ( r.id.textview1); btnstart.setonclicklistener (new view.onclicklistener () {@Overridepublic void OnClick (View V) { Myasynctask mytask=new myasynctask (); mytask.execute ();}); Btn.setonclicklistener (new view.onclicklistener () {@Overridepublic void OnClick (View v) {}});} Class Myasynctask extends asynctask<void, void, void>{@Overrideprotected void OnPreExecute () {tv.settext ("before"); Super.onpreexecute ();} @Overrideprotected void onprogressupdate (void ... values) {super.oNprogressupdate (values); String s=tv.gettext (). toString (); tv.settext (s+ "+");} @Overrideprotected void Doinbackground (void ... params) {try {for (int i=0;i<10;i++) {thread.sleep (1000); Publishprogress (null);}} Catch (interruptedexception e) {e.printstacktrace ();} Return null;} @Overrideprotected void OnPostExecute (void result) {tv.settext ("done"); super.onpostexecute (result);}}</pre><p><p>Asynctask parameters and how to use Them: a complete asynctask requires three pass-through parameters. For the first pass, execute () is passed to Doinbackground () at startup, such as which file needs to be copied, which server the data is uploaded to, etc., and the second pass is Doinbackground () in the call <span class="Apple-tab-span">publishprogress</span> () when passed to onprogressupdate () such as: the current download progress, has been downloaded to the server list, the third pass, is Doinbackground () after running the parameter to OnPostExecute (), such as the success of data Acquisition.<span class="Apple-tab-span"><br></span></p></p><p><p>Asynctask defines three generic type parameters, namely Params,progress and Result, that is, asynctask<params,progress,result>; The params is the parameter that initiates the execution of the task, such as the percentage of the HTTP request url;progress background execution, The result of the task that the result background performs, such as string, which is illustrated by a demo</p></p><p><p>As follows</p></p><p><p></p></p><p><p>The demo code is as follows</p></p><pre class="brush:java;gutter:true;">Package Com.example.asynctaskparams;import Android.app.activity;import Android.os.asynctask;import Android.os.bundle;import Android.view.view;import Android.widget.button;import Android.widget.TextView;public Class Mainactivity extends Activity {private mytask task;private Button btnstart,btnclose;private TextView txtcontext;@ overrideprotected void onCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( r.layout.activity_main); btnstart= (button) Findviewbyid (r.id.btnstart); btnclose= (button) Findviewbyid ( r.id.btnclose); txtcontext= (TextView) Findviewbyid (r.id.txtcontext); btnstart.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View v) {task=new mytask ();//task sends the parameter of the first task Task.execute (15);}); Btnclose.setonclicklistener (new view.onclicklistener () {@Overridepublic void OnClick (View v) {task.cancel (true); =null;txtcontext.settext ("Close");}}); @Overrideprotected void OnDestroy () {if (task!=null) {task.cancel (true);} Super.ondestroy ();} CLass MyTask extends asynctask<integer, Integer, boolean>{@Overrideprotected void OnPreExecute () { Txtcontext.settext ("start"); Super.onpreexecute ();} @Overrideprotected void onprogressupdate (Integer ... values) {//task uses the second parameter in this method body Txtcontext.settext ("" +values[0]); Super.onprogressupdate (values);} @Overrideprotected Boolean doinbackground (Integer ... Params) {//task uses the first parameter for (int I=0;i<params[0];i++) {// The task sends the second argument publishprogress (i); try {thread.sleep (+);} catch (interruptedexception e) {e.printstacktrace ()}} The task sends a third argument, return true; @Overrideprotected void OnPostExecute (Boolean Result) {//task uses the third parameter Txtcontext.settext ("" +result); Super.onpostexecute (result);}}}</pre><p><p> </p></p><p><p>Android Multithreading message processing mechanism</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