Android multithreading handler + runOnUithread + view. post + handler. post

Source: Internet
Author: User

Listview can be temporarily suspended...

Next, let's talk about the multithreading mechanism of android. When talking about multithreading, we can say that the famous android ANR (Application Not Responding) has two conditions for triggering ANR: 1. failed to respond to the next event after more than five seconds in the activity. 2. If BroadcastReceive exceeds 10 seconds, both conditions will trigger ANR.

The ANR of an activity is simulated below.

protected void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        findViewById(R.id.button1).setOnClickListener(new OnClickListener()        {            @Override            public void onClick(View v)            {                try                {                    Thread.sleep(10000);                }                catch (InterruptedException e)                {                    e.printStackTrace();                }            }        });    }

Running effect:

Not triggered:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1123306304-0.jpg "title =" not touch. jpg "/>

After triggering:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1123301639-1.jpg "title =" after the touch. jpg "/>


When users use this experience, it can be imagined that it will be very painful...

Someone will ask why there is a mechanism like ANR.

In fact, all the UI display in the android system is executed in the main thread. If there is time-consuming operation in the thread, other UI components in the thread will wait until the time-consuming end to start responding, therefore, to avoid this situation, android uses handler to put time-consuming operations in sub-threads for execution. When the end time is reached, the results of time-consuming operations are sent back to the main thread, so here we need to introduce the concept of inter-thread communication.


Amount (⊙ o ⊙ )... The more new concepts are written here .... Is it okay to solve it slowly...

In this case, it seems that the communication between threads is very painful. Actually, a method is called ....

Hey


Let's not talk about code first.

Private Handler mHandler = new Handler () {// parameter: Message is equivalent to a carrier of information and can transmit data from sub-threads to the main thread, that is, the so-called inter-thread communication... Public void handleMessage (android. OS. Message msg) {// This method is executed in the main thread. If you do not believe this method, you can log it... String result = (String) msg. obj; // switch (msg. what) // what is used to mark the information sent by the user {case 1: mTextView1.setText (result); // you must set the UI component in the main thread; otherwise, an error is reported... Break; case 2: mTextView2.setText (result); break; default: break ;}}; private TextView mTextView1; private TextView mTextView2; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); mTextView1 = (TextView) findViewById (R. id. textView1); mTextView2 = (TextView) findViewById (R. id. textView2); Button button1 = (Button) findViewById (R. id. button1); button1.setOnClickListener (listener); Button button2 = (Button) findViewById (R. id. button2); button2.setOnClickListener (listener);} private OnClickListener listener = new OnClickListener () {@ Override public void onClick (View v) {switch (v. getId () {case R. id. button1: new Thread () {public void run () {// simulate time-consuming operations try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();} String result = "result obtained from the network"; Message msg = new Message (); msg. what = 1; msg. obj = result; // sent to the main thread mHandler. sendMessage (msg); // textView. setText (result );}}. start (); Log. e ("MainActivity", "button1"); break; case R. id. button2: new Thread () {public void run () {// simulate time-consuming operations try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();} String result = "results obtained from the Database"; Message msg = new Message (); msg. what = 2; msg. obj = result; // sent to the main thread mHandler. sendMessage (msg );}}. start (); Log. e ("MainActivity", "button2"); break; default: break ;}}};

I will append the source code to the layout file of the article and leave it empty...

Running result:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/112330LJ-2.jpg "title =" result.jpg "/>


Handler... The Code project exceeds 2 mb. I put it on the 51cto Network Disk.

Link: handler



Next, let's talk about post. In fact, the view. post and handle. post methods are similar. They all pass in an object that implements the Runnable interface in the post method, which is implemented in the run method of this object.


Private TextView mTextView; private Button mButton; class Listener implements OnClickListener {@ Override public void onClick (View v) {switch (v. getId () {case R. id. button1: download (); break; default: break ;}}@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); mButton = (Button) findViewById (R. id. button1); MButton. setOnClickListener (new Listener ();} public void download () {new PlayThread (). start (); // enable the sub-Thread} class PlayThread extends Thread {@ Override public void run () {// This is the sub-Thread try {Thread. sleep (2000); // simulate time-consuming operations for downloading data from the network} catch (InterruptedException e) {e. printStackTrace ();} mButton. post (new Runnable () // the post method of view is used here {// The content here will be displayed in the main thread @ Override public void run () {mTextView. setText ("yes get the number Yes ~~~ ");}});}}


The runOnUiThread (Runnable action) method and handler. post (Runnable action) method are used in the same way as the view. post (Runnable action) method.

RunOnUiThread (Runnable action) is the activity method. Here, Runnable is also running in the main thread.

Handler. post (Runnable action) is the method in handler, Which is similar. Of course, if you can tell me the difference between them, I will also listen to each other and learn from each other. Thank you...






This article is from the "android_home" blog, please be sure to keep this http://yangzheng0809.blog.51cto.com/6024606/1271694

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.