Small knowledge of the Android thread and UI

Source: Internet
Author: User

1. Updating the UI regularly

You typically need code that is similar to a timed update UI, such as animation controls.

1.1 Multi-threaded Timing Change UI

Specifically, a new startup (not letting the UI thread sleep and stuck) a thread to time, then timed to notify UI modifications.

1.1.1 A new startup thread to perform tasks on a timed basis
    • Timer + timertask
    • New Boot Thread: Run Method: while (true) + Thread.sleep/systemclock.sleep

is essentially a new thread that clocks behind. Because a new non-UI thread is used to perform timings, the UI modifications need to be notified after the time arrives. For performance reasons, the UI controls on Android are not thread-safe, and then Google design only lets the UI thread (the main thread) directly modify the UI controls, and other non-UI threads are not able to reach the thread safety of the UI.

1.1.2 How UI controls are updated by non-UI threads
    • Runonuithread
    • Handler
    • View.postdelay

Runonuithread can be seen from a name that is specifically intended for use by other threads to change the UI. Handler is used for message passing between different threads, allowing the thread T1 to notify T2 to perform certain actions at the desired moment. This, of course, also fully satisfies the purpose of the [Non-UI thread regularly notifies the UI thread to change UI control State].

1.2 Handler timed Update UI

If you just want to complete "timed execution," You can use Handler.sendemptymessagedelayed (1,2000) without opening a new thread.

Called at the point where the scheduled task execution begins:

Handler.sendemptymessage ();

Handler rewrite handlemessage in the main thread:

Final int Update_anim = 1001;

boolean isanimfinish;

Handler Handler = new Handler() {

@Override

Public void handlemessage (Message msg) {

Switch (msg.what) {

Case Update_anim:

if (!isanimfinish) {

Update the code for the UI , changing the isanimfinish flag as appropriate in the code.

Handler.sendemptymessagedelayed (Update_anim, 2000);

}

break;

}

}

};

As you can see, opening a new thread is typically done with some non-UI but time-consuming operations, such as getting news data from the Web. And the timing task of such things handler can also be done.

2.Handler cross-thread communication 2.1 principle description

In order for other threads to send messages to notify the current thread to perform some tasks, the current thread thread can do this:

    • The current thread provides a unique MessageQueue that is used to receive a message that other threads have dropped in. MessageQueue maintains all messages using FIFO time sequence.
    • The current thread provides a unique looper to manage its MessageQueue, mostly by taking a message from it and sending it to the handler object that dropped the message into the queue.
    • The current thread can create one or more handler objects. Assume that handler_1 overrides its public void Handlemessage (Message msg) method as required. When Looper obtains a message from MessageQueue that calls Handler_1 's SendMessage method, it calls Handler_1 's handlemessage to process the message.

Looper and the MessageQueue are thread-only, of course there is no need for multiple-except to add trouble.

    • Other threads can encapsulate a message object as needed, calling Handler_1 's SendMessage so that handler_1 sends the message to the MessageQueue of its own thread, Soon this message was monitored by the looper of the thread, taken away and sent to handler_1 for processing.

Through the cooperation of the above Looper, MessageQueue, handler, each thread passes the handler to let other threads notify themselves to perform some actions as needed.

Handler can implement the communication between different threads, the default main thread has already provided the Looper and MessageQueue, so if you need to write a handler object, you can use handler in the newly opened other threads to let the main thread perform the operation. It is common to update UI controls.

Handler is created in which thread, it corresponds to which thread's looper, MessageQueue.

2.2 Let your thread start receiving messages

Other threads default Looper and MessageQueue are not ready and can be configured in the Run method with the following steps:

    • Call the Looper.prepare () method, which establishes the Looper instance and the corresponding MessageQueue.
    • Design your own handler object, mainly processing the message, then for the outside world to use it to want to MessageQueue send messages.
    • It is a good idea to call the Looper.loop () method to turn on looper monitoring of message queues. Indicates that other threads can send notifications.
2.3 Toast.show's Call

Essentially, the UI controls are modified, and ultimately the UI thread executes. For example, if we need to set the Text property of a textview in our thread, we can only use the UI thread's handler to send a message to the UI thread to execute. Or an easy way to use Runonuithread.

A special example is toast.show, which we can call in the Handlemessage method of the handler of our own thread. But also limited to handlemessage, Toast.show needs the current thread to have Looper and handler, and it is finally going to be executed in the UI thread.

3. Multi-threaded Update listview

Another example of a common "cross-threading Change UI" is network data loading, such as loading a news list into a ListView, and starting a new thread to avoid blocking the main threads and the card UI.

It is much more cost-effective to use non-UI threads to perform time-consuming operations than to start a thread to achieve the timer. The general routines are:

    • When new data is needed on the interface, a thread is started to fetch a batch of data from the network or locally, usually paging to get a reasonable set of data. The progress bar is displayed on the interface and makes some interfaces non-interactive.
    • After getting the data, call adapter's notifydatasetchanged (), which is a UI action that needs to be done using the "Non-UI thread to perform UI operations" technique.

The point of ListAdapter is to reuse a view object that is not visible on the screen and use Viewholder to avoid the overhead of Findviewbyid.

4.AsyncTask

There's nothing to say, a very typical start-up thread takes a time-consuming task, and then updates the UI, and almost most scenarios can use it to quickly implement functionality.

The general is:

    • Perform UI actions in OnPreExecute to display the progress bar.
    • Perform time-consuming tasks in Doinbackground and call publishprogress to update progress.
    • OnPostExecute using the result data, dismiss the progress bar.

You should create an instance of Asynctask in the UI thread and invoke its Execute method.

Small knowledge of the Android thread and UI

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.