Androidhandlerthread Full Parse (reprint)

Source: Internet
Author: User

Androidhandlerthread Full Parse

Reprint please indicate the source:
http://blog.csdn.net/lmj623565791/article/details/47079737;
This article is from: "Zhang Hongyang's Blog"

1. Overview

The recent changes in the stock market have also become a hot topic. Do you have any idea to make a real-time update of the stock market data app? Suppose we want to do a real-time update of the stock market data app, we can find a third-party stock market data interface, and then in our app every 1 minutes (the right time) to update the data, and then update our UI.

Of course, this article is not to teach you to do such an app, just to give a scene. Back to our handlerthread, we must have heard of Looper, Handler, message three relationships (if you do not understand, you can view the Android asynchronous message processing mechanism to give you a deep understanding of Looper, Handler, Message three relationships), in our UI thread silently serving us. In fact, we can learn from the UI thread Looper ideas, engage in sub-threading, also through handler, message communication, can be applied to many scenarios.

Yes, I've written a blog post about Android Handler asynchronous message processing mechanism to create a powerful picture loading class, this blog post in the sub-thread created the Looper,handler, the principle and handlerthread exactly the same, but I did not know that the class , but you can also learn as a handlerthread application scenario.

2. Handlerthread instances

below to see our simulation of the market trend of the code, in fact, very simple, just an activity

 PackageCom.zhy.blogcodes.intentservice;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.HandlerThread;ImportAndroid.os.Message;Importandroid.support.v7.app.AppCompatActivity;Importandroid.text.Html;ImportAndroid.widget.TextView;ImportCOM.ZHY.BLOGCODES.R; Public  class handlerthreadactivity extends appcompatactivity{    PrivateTextView Mtvserviceinfo;PrivateHandlerthread Mcheckmsgthread;PrivateHandler Mcheckmsghandler;Private BooleanIsupdateinfo;Private Static Final intMsg_update_info =0x110;//handler with UI thread management    PrivateHandler Mhandler =NewHandler ();@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_thread_handler);//Create a background threadInitbackthread ();    Mtvserviceinfo = (TextView) Findviewbyid (R.id.id_textview); }@Override    protected void Onresume()    {Super. Onresume ();//Start queryIsupdateinfo =true;    Mcheckmsghandler.sendemptymessage (Msg_update_info); }@Override    protected void OnPause()    {Super. OnPause ();//Stop queryIsupdateinfo =false;    Mcheckmsghandler.removemessages (Msg_update_info); }Private void Initbackthread() {Mcheckmsgthread =NewHandlerthread ("Check-message-coming");        Mcheckmsgthread.start (); Mcheckmsghandler =NewHandler (Mcheckmsgthread.getlooper ()) {@Override             Public void Handlemessage(Message msg) {checkforupdate ();if(Isupdateinfo) {mcheckmsghandler.sendemptymessagedelayed (Msg_update_info, +);    }            }        }; }/** * Simulate data from the server */    Private void checkforupdate()    {Try{//Simulation time-consumingThread.Sleep ( +); Mhandler.post (NewRunnable () {@Override                 Public void Run() {String result ="In real-time update, current market index: <font color= ' red ' >%d</font>"; result = String.Format (result, (int) (Math.random () * the+ +));                Mtvserviceinfo.settext (html.fromhtml (result));        }            }); }Catch(Interruptedexception e)        {E.printstacktrace (); }    }@Override    protected void OnDestroy()    {Super. OnDestroy ();//Release ResourcesMcheckmsgthread.quit (); }}

You can see that we are in OnCreate, to create and launch the Handlerthread, and to associate a mcheckmsghandler. We then opened and paused our query in Onresume and OnPause, and finally released the resources in Ondestory.

This enables us to query the latest data every 5s go to the server, and then update our UI, of course, we here through the Thread.Sleep () simulation time-consuming, return a random number, we can easily replace the real data interface.

Layout Library

<Relativelayout xmlns:android="Http://schemas.android.com/apk/res/android"                Xmlns:tools="Http://schemas.android.com/tools"                Android:layout_width="Match_parent"                Android:layout_height="Match_parent"                Android:paddingleft="@dimen/activity_horizontal_margin"                Android:paddingright="@dimen/activity_horizontal_margin"                Android:paddingtop="@dimen/activity_vertical_margin"                Android:paddingbottom="@dimen/activity_vertical_margin">    <TextViewandroid:id="@+id/id_textview"android:text="Loading the market index ... "android:layout_width="wrap_content "android:layout_height="wrap_content " />                                </relativelayout>

Run

Don't ask why I want to use red!!!

OK, of course, our effect is monotonous, but you can expand it, for example, the ListView displays the stock data that the user is following. or other data that needs to be constantly tested for updates.

See this, are you curious, how is Handlerthread's interior done? Actually very simple, if you have seen the Android asynchronous message processing mechanism let you deeply understand Looper, Handler, message three relations estimate sweep a few eyes will be.

Handlerthread Source Code Analysis

For all Looper,handler related details, refer to the above article for a unified reference.

We gently opened the source of Handlerthread, remember that we are through

new HandlerThread("check-message-coming"

Create and start the object, then take a casual glance:

 PackageAndroid.os; Public  class handlerthread extends Thread {    intmpriority;intMtid =-1; Looper Mlooper; Public Handlerthread(String name) {Super(name);    mpriority = Process.thread_priority_default; }protected void onlooperprepared() {    }@Override     Public void Run() {Mtid = Process.mytid (); Looper.prepare ();synchronized( This) {Mlooper = Looper.mylooper ();        Notifyall ();        } process.setthreadpriority (mpriority);        Onlooperprepared ();        Looper.loop (); Mtid =-1; }

See what, in fact we are initializing and starting a thread, then we look at the run () method, you can see that the method called Looper.prepare (), Loop.loop ();

Prepare (), a Looper object is created in, and the object is placed in a variable (sthreadlocal) within that thread scope, and during the construction of the Looper object, a MessageQueue is initialized as the Looper object member variable.

Loop () is turned on, and the constant loop takes the message from the MessageQueue, and when there is no message, it will block and wake up when the message arrives. If you don't understand what I'm saying, refer to the article recommended above.

Next, we created a mcheckmsghandler that was created like this:

new Handler(mCheckMsgThread.getLooper())

Corresponding source code

public  Looper getlooper  () {if  (!isalive ()) {return  null ;        } //If the thread has been started, wait until the Looper have been created.  synchronized  (this ) {while  (isAlive () && mlooper = = null) {try  {wait (); } catch  (Interruptedexception e) {}}} return  mlooper; }

Mcheckmsgthread.getlooper () returns the Mlooper that we created in the Run method.

So what about the handler structure, is actually holding a pointer to the Looper.mqueue object in the handler, when handler calls the SendMessage method, it actually inserts a message into the Mqueue, and then Looper.loop () takes out the execution.

Well, here we have the analysis, in fact, a few lines of code; But one thing I would like to mention:

If you're careful, you'll find out that the Run method has a notifyall () after Mlooper is created, and there's a wait () in Getlooper (). Because the mlooper is executed in a thread, and our handler is initialized in the UI thread, that is, we have to wait until Mlooper is created to properly return getlooper (); Wait (), notify () is to solve the synchronization problem of these two threads.

However, I am very fond of using semaphore for this kind of synchronization problem between threads.

Remember that the magic of the Android Handler asynchronous message processing mechanism creates a powerful picture loading class with a similar description:

If you are more careful, you may find there are some semaphore operation code, if you do not understand what is the semaphore, you can refer to: Java concurrency topic: Semaphore Implementation of mutual exclusion and connection pooling. Briefly say Msemaphore (signal number 1), because Mpoolthreadhander is actually a child thread initialization, So I called Msemaphore.acquire before the initialization to request a semaphore, and then released the semaphore after initialization, why would I do that? Since the main thread may be used immediately to mpoolthreadhander, but Mpoolthreadhander is initialized in the sub-thread, although very fast, but I can not be assured that the main thread was initialized at the end of the use.

Ha, there were also many people asked, why use this semaphore, here I think we should be clear. I suppose I really handerthread this class at the time, and maybe the previous code would have made it a lot easier.

By the way, you may ask what advantages are compared to a timer?

Refer to this article directly: Handler vs Timer

ok~~

Welcome to follow my Weibo http://weibo.com/u/3165018720

Group No.: 463081660, welcome into the group

Public Number: Hongyangandroid
(Welcome attention, the first time to push the blog post information)

Original link This article by Bean John Blog Backup expert remote One click release

Androidhandlerthread Full Parse (reprint)

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.