Communication between Android threads

Source: Internet
Author: User

Android, only the main thread can modify the UI value, Workthread can not be modified. So running a more time-consuming program in Workthrean, that is, getting the data in Workthread, then sending the data to the main thread, and then modifying the UI.

Follow the above ideas to understand the communication between threads in Android.

1. Create a new Testhandler class, inherit to Handler,

1) The replication Handlermessage method to obtain the information in the message queue;

// New Handler Object  New  Testhandler (); // Testhandler class class extends handler{       @Override        publicvoid  handlemessage (Message msg) {                    }} 

2, Workthread class

1) inherit to thread;

2) The process of sending data in this area;

3) Handler's Obtainmessage method can obtain the message in the message queue;

4) Handler SendMessage method: Send data to the main thread;

Specific:

classTestthreadextendsthread{@Override Public voidrun () {Try {                 //things to do in the WorkthreadThread.Sleep (2000); }            Catch(interruptedexception e) {e.printstacktrace (); }            finally{                //send a message to the main threadString s = "Test String"; Message msg=Handler.obtainmessage (); Msg.obj=s;           Handler.sendmessage (msg); }        }    }

3. The function that is implemented after compiling is

1) Press the button to start the Workthread thread;

2) processing in the thread, get data, and then send the data to the main thread;

3) The main thread to obtain data, and then modify the UI;

4, after in-depth can be workthread to obtain the network data, and then sent to the main thread, modify the UI, so as to display to the user.

5, just learn Android soon, all over the description may be inappropriate, later found to go back to modify .....

Communication between Android threads

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.