Handlerthread Use Instances

Source: Internet
Author: User
This article we will introduce to you in the future Handlerthread this class, we used to use a thread to perform a time-consuming task always new thread to run, when the task is finished, the thread will be automatically destroyed, if again by the new task, we have to create new thread .... We assume such a scenario, we use the ListView to load the graph list, when we swipe down, it is necessary to constantly request network resources, that is, the need to constantly thread to load network resources, if each time a new thread, which is obviously unreasonable, then what to do. I believe everyone should use the picture load frame imageloader, in fact, imageloader internal is through the handler+looper+thread to achieve, the internal maintenance of a thread pool, through the handler+ Looper+thread constructs a recurring thread, each time a task is taken out of which the task is put to the thread pool to execute, not always waiting, until a new task is put in, if the task is too many to join the waiting queue, until one of the threads executes, from the waiting queue to get the next task to perform, This avoids the resource consumption caused by too many thread creation. Of course, the implementation of Handler+looper+thread is not the focus of this discussion, we are to discuss its implementation of the replacement-handlerthread, inherited from thread, the essence is thread, it differs from the normal thread is that It has a Looper member variable. Its interior is achieved through Thread+looper, and plainly Handlerthread is that Android has packaged a thread that has its own looper, and we can use it to perform some time-consuming tasks. Let's take a look at the use steps of Handlerthread and provide you with a use case: I. Steps to use Handlerthread 1. Create an Instance object [Java]View plain copy handlerthread handlerthread = new Handlerthread ("Downloadimage"); The main function of the parameter is to mark the name of the current thread, which can be any string. 2. Start the Handlerthread thread [Java]View plain copy//must first turn on thread Handlerthread.start (); This is where we build a looping thread. So how do we put a time-consuming asynchronous task into the Handlerthread thread to execute it. Next look at the following steps: 3. Building a circular message processing mechanism [Java]View Plain Copy/** * This Callback runs on a child thread */class Childcallback implements Handler.callback {@Override             public boolean handlemessage (Message msg) {//the corresponding network request//notification main thread in the child thread to update the UI             Muihandler.sendmessage (MSG1);         return false; }} Building Asynchronous Handler [Java]View Plain Copy//Sub-thread Handler Handler childhandler = new Handler (Handlerthread.getlooper (), New Childcallback ()); The 3rd step is to build a handler that can be used for asynchronous operations and pass the Handlerthread Looper object and callback interface class created earlier as parameters to the current handler. In this way, the current asynchronous Handler has the Handlerthread Looper object, and the Handlermessage method handles the time consuming task, looper+handler+messagequeue+ The thread asynchronous loop mechanism is built to complete. Let's take a look at a use case Two. Use cases of Handlerthread [Java] View Plain Copy package com.zejian.handlerlooper;   import android.app.activity;   import android.graphics.bitmap;   import android.graphics.bitmapfactory;   Import  android.os.Bundle;   import android.os.handler;   import  android.os.handlerthread;   import android.os.message;   import  android.widget.imageview;   import com.zejian.handlerlooper.model.imagemodel;   Import  com.zejian.handlerlooper.util.LogUtils;   import java.io.bufferedinputstream;   import java.io.ioexception;   import java.net.httpurlconnection;   import  java.net.url;  /**   * Created by zejian on 16/3/5.   */    public class handlerthreadactivity extends activity {        /**       *  picture Address collection, images from network .       */        private String url[]={                 "Http://img.my.csdn.net/uploads/201407/26/1406383299_1976.jpg",                 "http://img.my.csdn.net/uploads/201407/26/ 1406383291_6518.jpg ",               " http ://img.my.csdn.net/uploads/201407/26/1406383291_8239.jpg ",                 "Http://img.my.csdn.net/uploads/201407/26/1406383290_9329.jpg",                 "http://img.my.csdn.net/uploads/ 201407/26/1406383290_1042.jpg ",                 "Http://img.my.csdn.net/uploads/201407/26/1406383275_3977.jpg ",                 "Http://img.my.csdn.net/uploads/201407/26/1406383265_8550.jpg",                 "http://img.my.csdn.net/uploads/201407/26/ 1406383264_3954.jpg ",               " http ://img.my.csdn.net/uploads/201407/26/1406383264_4787.jpg ",                 "Http://img.my.csdn.net/uploads/201407/26/1406383264_8243.jpg",                 "http://img.my.csdn.net/uploads/ 201407/26/1406383248_3693.jpg ",                 "Http://img.my.csdn.net/uploads/201407/26/1406383243_5120.jpg",                 "Http://img.my.csdn.net/uploads/201407/26/1406383242_3127.jpg",                 "http://img.my.csdn.net/uploads/201407/26/1406383242_ 9576.jpg ",               "/http Img.my.csdn.net/uploads/201407/26/1406383242_1721.jpg ",                 "Http://img.my.csdn.net/uploads/201407/26/1406383219_5806.jpg",                "http://img.my.csdn.net/uploads/201407 /26/1406383214_7794.jpg ",               " Http://img.my.csdn.net/uploads/201407/26/1406383213_4418.jpg ",                 "Http://img.my.csdn.net/uploads/201407/26/1406383213_3557.jpg",    &NBSP;&NBSP;&NBSP;&NBSP;         "Http://img.my.csdn.net/uploads/201407/26/1406383210_8779.jpg ",               " http://img.my.csdn.net/ Uploads/201407/26/1406383172_4577.jpg "       };        private ImageView imageView;       private Handler  Muihandler = new handler () {           @ override           public void handlemessage ( MESSAGE&NBSP;MSG)  {                LOGUTILS.E ("Times:" +msg.what);                ImageModel model =  (Imagemodel)  msg.obj;              &Nbsp; imageview.setimagebitmap (model.bitmap);            }       };        @Override         protected void oncreate (bundle savedinstancestate)  {            super.oncreate (savedinstancestate);            setcontentview (r.layout.activity_handler_thread);            imageView=  (ImageView)  findviewbyid (r.id.image);            //Creating asynchronous handlerthread            handlerthread handlerthread = new handlerthread ("Downloadimage");            //must first turn on threads             handlerthreaD.start ();           //sub-thread handler            handler childhandler = new handler ( Handlerthread.getlooper (), New childcallback ());            for (int i=0;i<10;i++) {                //every 1 seconds to update pictures                 Childhandler.sendemptymessagedelayed (i,1000*i);           }        }       /**        *  the callback runs on sub-threads        */       class  ChildCallback implements Handler.Callback {             @Override    &NBSp;       public boolean handlemessage (Message msg)  {                //Network requests in sub-threads                bitmap bitmap=downloadurlbitmap ( Url[msg.what]);               imagemodel  imagemodel=new imagemodel ();                imageModel.bitmap=bitmap;                imageModel.url=url[msg.what];                message msg1 = new message ();                msg1.what = msg.what;                msg1.obj =imageModel;                //notify the main thread to update ui                muihandler.sendmessage (MSG1);                return false;           }        }       private Bitmap  Downloadurlbitmap (string urlstring)  {            httpurlconnection urlconnection = null;            BufferedInputStream in = null;            Bitmap bitmap=null;           try {        &Nbsp;       final url url = new url (urlString);                urlConnection =  (httpurlconnection)  url.openconnection ();                in = new bufferedinputstream (Urlconnection.getinputstream (),  8  * 1024);               bitmap= Bitmapfactory.decodestream (in);           } catch  ( Final ioexception e)  {                e.printstacktrace ();           } finally  {               if  ( Urlconnection != nuLL)  {                   

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.