Android updates the Ui in several ways and insights, and androidui in several ways

Source: Internet
Author: User
Tags sendmsg

Android updates the Ui in several ways and insights, and androidui in several ways
World in code

Draw your own android learning path with text notes

  Reprinted, Please retain the source by QiaoHttp://blog.csdn.net/qiaoidea/article/details/45115047

Android update Ui (1) android ui Thread Check Mechanism
Android update Ui (2) android thread update UI Mechanism

1. Brief Introduction

First, paste an error exception that we are most likely to encounter when developing Android.AndroidRuntimeException:"Only the original thread that created a view hierarchy can touch its views"
The specific cause is that when we make changes to the ui, Android checks whether our current operation thread is a UI thread. If not, this exception is reported. (For details, see the checkThread method of the ViewRootImpl class ).

2. Solution

So how should we update the Ui? Here we will briefly use and describe Handler. First, briefly describe the concept: Adroid will create a UiThread main thread at runtime to control the display, update and control interaction of the UI interface. Other threads push Message events such as update logic to the MessageQueue of the main thread through handler, and finally process these Message events in an orderly manner by the main thread ), updates and controls the interface.
This article describes how to update the UI and how to use it. For details about the principles of the update process, refer to the followingAndroid advanced Ui update.
The common methods are as follows:
-Handler. sendMessage ();
-Handler. post ();
-RunOnUiThread () can be used in an activity ();
-You can view. post () in the subview ()

In fact, the entire process processing logic of the following methods is basically based on the first one. It is encapsulated as a message event object that is sent to the queue and processed in an orderly manner, but android encapsulates the method for us.

3. Practice3.1 handler. senMessage () + handler. dispatchMessage ()

Define the handler of the main thread in the activity (the Sub-thread can also define the handler, of course, the message pump logoff is required for rotation) to implement the dispatchMessage method to process the message object. After the sub-thread processing logic is complete, the object encapsulates the content into a message and sends the message through handler. senMessage.
Sample Code:
A. Define the code logic handler and dispatchMessage methods for changing the ui.

/*** Use message to carry result data change ui * first define the main thread handler and the method for updating data */private static final int UPDATE_TITLE = 0; // update the title flag private Handler mainHandler = new Handler () {public void dispatchMessage (android. OS. message msg) {if (msg. what = UPDATE_TITLE) {String title = msg. getData (). getString ("Result"); titleView. setText (title) ;}else {// other messages }};};

B. The part of the data to be processed, for example, some time-consuming operations, are executed in the Child thread, and then handler. senMessage () is called ()

New Thread () {@ Override public void run () {// your processing logic. Here, a simple sleep for one second this. sleep (1000); // notification update UI // Message msg = new Message (); // we can use the constructor to create a Message, but to save memory resources, we should use Message. obtain () obtains the empty Message object Message msg = mainHandler from the Message pool. obtainMessage (); msg. what = UPDATE_TITLE; Bundle bundle = new Bundle (); // message data entity bundle. putString ("Result", "sendMsg -- Result"); msg. setData (bundle); // mainHandler. sendMessage (msg); // If Message is used. obtain () We can directly msg. sendToTarget ();}}. start ();

The Message object is mentioned here.(For more information, see Android Ui update)

Parameters that can be used for data transmission:

  • Int what;
  • Int arg1;
  • Int arg2;
  • Object obj;
  • Bundle data;

Used for callback

  • Runnable callback;

Generally, to make the code logic clearer and easier to understand, I prefer to update the Ui by calling callback directly (solution 2/3/4 ). Solution 1 can be simply optimized
Define handler directly

private Handler mainHandler= new Handler();

Send message

New Thread () {@ Override public void run () {try {// your processing logic. Here, sleep for one second. this. sleep (1000); // use obtain msg = Message. obtain (mainHandler, new Runnable () {@ Override public void run () {titleView. setText ("sendMsg -- Result") ;}}); msg. sendToTarget ();} catch (InterruptedException e) {e. printStackTrace ();}}}. start ();
3.2 handler. post ()

The second method of solution 1 can be simplified

New Thread () {@ Override public void run () {try {// your processing logic. Here, sleep for one second. this. sleep (1000); mainHandler. post (new Runnable () {@ Override public void run () {// your processing logic titleView. setText ("postRunnable -- Result") ;}});} catch (InterruptedException e) {e. printStackTrace ();}}}. start ();
3.3 runOnUiThread ()

The preceding scheme can be further simplified in the activity. You can directly call the runOnUiThread () method without using the new Handler object.

/*** Use runOnUiThread of activity */new Thread () {@ Override public void run () {try {// your processing logic. Here, a simple sleep second this. sleep (1000); runOnUiThread (new Runnable () {@ Override public void run () {titleView. setText ("runOnUiThread -- Result") ;}});} catch (InterruptedException e) {e. printStackTrace ();}}}. start ();
3.4 view. post ()

Of course, if you have a subview or custom view, you can directly use the view. post () method after processing the logic.

New Thread () {@ Override public void run () {try {// your processing logic. Here, sleep for one second. this. sleep (1000); viewPostBtn. post (new Runnable () {@ Override public void run () {titleView. setText ("viewPost -- Result") ;}});} catch (InterruptedException e) {e. printStackTrace ();}}}. start ();

In summary, updating the view does not seem so difficult to use ..
The source code file is attached.
Click to download source code

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.