Android Studio Learning Essay-ui threading blocking and optimization

Source: Internet
Author: User

When we use a mobile phone, we often encounter a problem: first the card to die, and then out of the program is not responding, whether to turn off the prompt (of course, we may be poor performance of the phone =. =) This is caused by the blocking of threads, where I tell about the UI thread, the generic handler takes time-consuming action in the UI thread, which causes the UI thread to block, when the UI thread is blocked, the screen appears stuck, the user experience becomes very poor when the thread blocks more than 5s, The Android system may intervene, and a popup dialog asks if it is closed. How to solve it?

Solution One: Create a new thread

I created a button and a textview in the UI view

 button button=  (button) Findviewbyid (R.id.button);        TextView textview=  (TextView) Findviewbyid (R.id.textview);        Translateanimation animation=new translateanimation (0,200,0,0 );        Animation.setrepeatcount (3 );        Animation.setduration (+ );      Textview.setanimation (animation); Here I let TextView move animation Button.setonclicklistener when entering the app (new  View.onclicklistener () {@Override public void OnClick (Final View v) {//Listen button click on new Thread (new Runnable () {//Create a new thread @Override public void Run () {try  {thre              Ad.sleep ();//Here I let the thread take a time-consuming operation} catch  (Interruptedexception e) {
E.printstacktrace ();
} }). Start (); }
});

The above code I create a new thread to implement time-consuming, but the actual process can not be just a time-consuming operation, let us add two sentences in the new thread,TextView view= (TextView) v; view.settext ("" +100);(gets to the current control and sets its text to 100) now Let's try this program again, this time the program again error

Only the original thread, created a view hierarchy can touch its views.

Only the thread that created the view can modify it.

In fact, Google has two suggestions, it can also be said that the rules

There is simply the rules to Android's single thread model: does    not block the UI thread//don't block the UI thread do not    acces s the Android UI Toolkit from outside the UI thread//do not set the components in view on other threads outside the UI thread

So many people have doubts, is this not a contradiction? Google also provides us with a solution

Solution One: View.post

The above code went wrong because we called UI controls outside the UI, and now we add code after the Try{}catch () {} statement.

1      V.post (new  Runnable () {2                           @Override3public                              void  Run () {4                                TextView view=(TextView) v; 5                                View.settext ("" +Sun); 6                            }7                        });

This code commits my statement to the UI thread; But View.post has some drawbacks.

Redundancy, poor readability, poor maintainability

There is also an alternative solution for this.

Solution Two: Asynctask

Asynctask and Post methods are similar

  Private classDownloadimagetaskextendsAsynctask<string,void,integer>{        protectedInteger Doinbackground (string...urls) {Try{Thread.Sleep (5000); }Catch(interruptedexception e) {e.printstacktrace (); }            intsun=100; returnSun; }        protected voidonpostexecute (Integer sum) {Button2.settext (""+sum); }    }

Button2.setonclicklistener (new  View.onclicklistener () {            @Override            public  void  OnClick (View v) {                new  downloadimagetask (). Execute ();                }           );

We now create a method externally and then reference it in the OnClick event of the button.

Android Studio Learning Essay-ui threading blocking and optimization

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.