Android Studio-UI thread blocking and optimization, android-ui

Source: Internet
Author: User

Android Studio-UI thread blocking and optimization, android-ui

When using a mobile phone, we often encounter a problem: First we get stuck, and then jump out of the program without a response, whether to close the prompt (of course, it may be that our mobile phone performance is too poor =. =) This is caused by thread blocking. Here I will introduce the UI thread. Generally, the handler will execute time-consuming operations in the UI thread, which causes UI thread blocking, when the UI thread is blocked, the screen will become stuck, and the user experience will become very poor. When the thread is blocked for more than 5 s, the android system may intervene. A dialog box is displayed asking if it is disabled. How can this problem be solved?

Solution 1: 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,); animation. setRepeatCount (3); animation. setduration( 2000); textView. setAnimation (animation); // here I want textView to move the animation button when entering the app. setOnClickListener (new View. onClickListener () {@ Override public void onClick (final View v) {// click to listen to the button new Thread (new Runnable () {// create a new Thread @ Override public void run () {try {Thread. sleep (5000); // here I want the thread to perform time-consuming operations} catch (InterruptedException e ){
E. printStackTrace ();
}}}). Start ();}
});

The above Code creates a new thread to implement time-consuming operations, but the actual process cannot be a time-consuming operation. Let's add two sentences in the new thread, textView view = (TextView) v; view. setText ("" + 100); (get the current control and set its text to 100) Now let's try this program again, and at this time the program reports an error

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

 

Only the thread that creates the view can modify the view.

In fact, Google has two suggestions, that is, rules.

There are simply two rules to Android's single thread model: do not block the Ui thread // Do not block the UI thread Do not access the Android UI toolkit from outside the UI thread // Do not set components in the view in other threads outside the UI thread

So many people have doubts. Isn't that a conflict? Google also provides us with solutions

Solution 1: view. post

The above code error occurs because the thread outside the UI calls the UI control. Now, we add the code after the try {} catch () {} statement.

1      v.post(new Runnable() {2                            @Override3                            public void run() {4                                TextView view=(TextView)v;5                                view.setText(""+sun);6                            }7                        });

 

This code submits my statements to the UI thread. However, view. post also has some disadvantages.

Redundancy, poor readability, and poor maintainability

For this reason, the official team also provides another solution.

Solution 2: AsyncTask

The AsyncTask and post methods are similar.

  private class DownloadImageTask extends  AsyncTask<String ,Void,Integer>{        protected Integer   doInBackground(String...urls){            try{                Thread.sleep(5000);            }catch (InterruptedException e){                e.printStackTrace();            }            int sun=100;            return  sun;        }        protected void onPostExecute(Integer sum){            button2.setText(""+sum);        }    }

 

button2.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                new DownloadImageTask().execute();                }           });

 

Create a method externally and reference it in The onClick event of the button.

Related Article

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.