android--Multi-Thread handler

Source: Internet
Author: User

Objective

The Android messaging mechanism is another form of "event handling," a mechanism designed to solve multi-threaded problems in Android applications, where activity-initiated threads are not allowed to access the UI components in the activity. This causes the newly started thread to fail to change the property values of the UI component. But in real-world development, many places need to change the property values of UI components in a worker thread, such as downloading Web images, animations, and so on. This blog mainly introduces how handler sends and handles messages delivered on threads, and explains several ways of transmitting data to a message, and finally demonstrates it with a small demo.

Handler

Handler, which inherits directly from object, a Handler allows the sending and processing of a message or Runnable object and is associated to the MessageQueue of the main thread. Each handler has a separate thread and is associated to a thread of Message queuing, meaning that a handler has an intrinsic message queue. When an handler is instantiated, it is hosted on a thread and message queue thread, which handler messages or runnable into the message queue and extracts messages or runnable from the message queue to manipulate them.

Handler has two main functions:

    • Sends a message in a worker thread.
    • Gets and processes messages in the UI thread.

As described above, handler can put a message object or Runnable object into the message queue, and then get a message in the UI thread or execute the Runnable object, so handler to press into the message queue has two major systems, Post and SendMessage:

    • Post:post allows a Runnable object to be enqueued into the message queue. It has the following methods: Post (Runnable), Postattime (Runnable,long), postdelayed (Runnable,long).
    • Sendmessage:sendmessage allows a Message object containing the message data to be pressed into the queue of messages. Its methods are: sendemptymessage (int), sendMessage (message), Sendmessageattime (Message,long), sendmessagedelayed (message, Long).

As can be seen from the various methods above, both post and SendMessage have several methods, they can set the Runnable object and the Message object to be enqueued into the message queue, whether it is executed immediately or deferred.

  

Post

For Handler post, it passes a Runnable object to the message queue, and in this Runnable object, rewrite the run () method. In this run () method, it is common to write operations that need to be on the UI thread.

In handler, the method of post is as follows:

    • Boolean post (Runnable R): A Runnable is enqueued into the message queue, and the UI thread executes immediately after the object is fetched from the message queue.
    • Boolean postattime (Runnable r,long uptimemillis): Queues a Runnable into a message queue, which is executed at a specific time after the UI thread takes the object out of the message queue.
    • Boolean postdelayed (Runnable r,long delaymillis): Queues a Runnable into a message queue and delays delaymills seconds after the UI thread takes the object out of the message queue
    • void Removecallbacks (Runnable R): Removes a Runnable object from the message queue.

Below is a demo that explains how to modify the properties of a UI component in a newly-started thread via the handler post method:

 1 package Com.bgxt.datatimepickerdemo; 2 3 Import android.app.Activity; 4 Import Android.os.Bundle; 5 Import Android.os.Handler; 6 Import Android.view.View; 7 Import Android.widget.Button; 8 Import Android.widget.TextView; 9 public class HandlerPostActivity1 extends Activity {One private Button btnmes1,btnmes2;12 private TextView TvM ESSAGE;13//Declare a Handler object in the private static Handler handler=new Handler (); @Override17 protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout        . message_activity);         btnmes1= (Button) Findviewbyid (r.id.btnmes1); btnmes2= (Button) Findviewbyid (r.id.btnmes2); 23 Tvmessage= (TextView) Findviewbyid (r.id.tvmessage), Btnmes1.setonclicklistener (New View.onclicklistener ()                 {@Override27 public void OnClick (View v) {28//New START a child thread 29 New THread (New Runnable () {@Override31 public void run () {32                         Tvmessage.settext ("..."); 33//above the operation will be error-able to access the UI component in the child thread, the UI component's properties must be accessed in the UI thread 34                    Use post to modify the Text property of the UI component Tvmessage Handler.post (new Runnable () {                                 @Override37 public void Run () {38 Tvmessage.settext ("Use Handler.post to send a piece of execution to the message queue in a worker thread, executed in the main thread.")                        ");                                39}40}); }42}). Start ();}44}); btnmes2.setoncli Cklistener (New View.onclicklistener () {@Override49 public void OnClick (View v) {      New Thread (Runnable () {51               @Override52 public void Run () {53//Modify the UI component using postdelayed mode Tvmes                             Sage's Text property value 54//And Delay 3S execution handler.postdelayed (new Runnable () {56                                 @Override58 public void Run () {59 Tvmessage.settext ("uses handler.postdelayed to send a piece of execution to the message queue in a worker thread, delaying 3S execution in the main thread.    ");                        60 61}62}, 3000); }64}). Start (); 65 66}67}); 68}69}

android--Multi-Thread handler

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.