HandlerThread usage for android

Source: Internet
Author: User

For more information, see http://blog.csdn.net/lskshz/article/details/25364909yi ..

HandlerThread is inherited from the Thread. When the Thread is enabled, that is, after it runs the run method,

The Thread also creates a loose containing a message queue and provides its own get method for the loose object. This is the only difference between it and a common Thread.

Ii. Benefits

Why HandlerThread.

1. If this problem occurs during development, use new Thread () {...}. start ()

Enabling a subthread in this way will create multiple anonymous threads, making the program running slower and slower,

HandlerThread's built-in logoff allows him to reuse the current thread multiple times through messages, saving money;

2. The logoff in the Handler class provided by the android system is bound to the Message Queue of the UI thread by default,

For non-UI threads that want to use the message mechanism, logoff within HandlerThread is the most suitable, and it will not interfere with or block the UI thread.


Iii. Usage of HandlerThread since the essence is Thread, why is a Handler added in front of it? In android, the Handler class is essentially to retrieve messages from its internal logoff, and then trigger the handleMessage method of its internal Callback interface, so that users can implement specific message processing.

HandlerThread itself comes with logoff, as long as it implements the Callback interface,

HandlerThread can also process messages sent by its own thread,

Fully implement message processing at a lower cost in non-UI threads.

Iv. Sample Code
MyHandlerThread  myHandler = new MyHandlerThread("lsk");myHandler.setPriority(Thread.MIN_PRIORITY);myHandler.start();Handler handler = new Handler(myHandler.getLooper(), myHandler);
 
class MyHandlerThread extends HandlerThread implements Callback {public MyHandlerThread(String name) {super(name);}@Overridepublic boolean handleMessage(Message msg) {}}




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.