Android Handle detailed 3 Threadhandler

Source: Internet
Author: User

On the basis of Android handle detailed 2, we come to learn Threadhandler

The essence of Threadhandler is the implementation of the Android handle detailed 2

Handlerthread is actually a thread, and the thread internally creates a Looper object, which is a looper unique to the child thread, used to take out and handle the message.

Let's take a look at the use of Handlerthread

Privatenew handlerthread ("Handlerthread"); Handlerthread.start ();

Create the handler, using Mhandlerthread.getlooper () to get the Looper object created internally Handlerthread: We'll get the Looper object passed to the handler object through the constructor, This allows the handle object to get the message Queue member variable of the Looper object, which is a member variable of the Looper object

Final New Handler (Mhandlerthread.getlooper ()) {            @Override            publicvoid  handlemessage ( Message msg) {                System.out.println ("received message");            }        };

Then create a new sub thread to send the message:

New Thread (new  Runnable () {            @Override            publicvoid  run () {                  Try  {                    thread.sleep (+);   Analog time-consuming operation                    handler.sendemptymessage (0);                 Catch (interruptedexception e) {                    e.printstacktrace ();}}}        ). Start ();

Finally, be sure not to forget to release in OnDestroy to avoid memory leaks:

@Override     protected void OnDestroy () {        super. OnDestroy ();        Mhandlerthread.quit ();    }

is not quite the classics must make Handleer's internal realization principle very clear

Android Handle detailed 3 Threadhandler

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.