Android HandlerThread
Posted 胖子luffy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android HandlerThread相关的知识,希望对你有一定的参考价值。
HandlerThread继承Thread,是一个包含了Looper的Thread,方便了子线程之间的通信。
源码:
/*
* Copyright (C) 2006 The android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.os;
/**
* Handy class for starting a new thread that has a looper. The looper can then be
* used to create handler classes. Note that start() must still be called.
*/
public class HandlerThread extends Thread
int mPriority;
int mTid = -1;
Looper mLooper;
public HandlerThread(String name)
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT;
/**
* Constructs a HandlerThread.
* @param name
* @param priority The priority to run the thread at. The value supplied must be from
* @link android.os.Process and not from java.lang.Thread.
*/
public HandlerThread(String name, int priority)
super(name);
mPriority = priority;
/**
* Call back method that can be explicitly overridden if needed to execute some
* setup before Looper loops.
*/
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;
/**
* This method returns the Looper associated with this thread. If this thread not been started
* or for any reason is isAlive() returns false, this method will return null. If this thread
* has been started, this method will block until the looper has been initialized.
* @return The looper.
*/
public Looper getLooper()
if (!isAlive())
return null;
// If the thread has been started, wait until the looper has been created.
synchronized (this)
while (isAlive() && mLooper == null)
try
wait();
catch (InterruptedException e)
return mLooper;
/**
* Quits the handler thread's looper.
* <p>
* Causes the handler thread's looper to terminate without processing any
* more messages in the message queue.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the @link Handler#sendMessage(Message) method will return false.
* </p><p class="note">
* Using this method may be unsafe because some messages may not be delivered
* before the looper terminates. Consider using @link #quitSafely instead to ensure
* that all pending work is completed in an orderly manner.
* </p>
*
* @return True if the looper looper has been asked to quit or false if the
* thread had not yet started running.
*
* @see #quitSafely
*/
public boolean quit()
Looper looper = getLooper();
if (looper != null)
looper.quit();
return true;
return false;
/**
* Quits the handler thread's looper safely.
* <p>
* Causes the handler thread's looper to terminate as soon as all remaining messages
* in the message queue that are already due to be delivered have been handled.
* Pending delayed messages with due times in the future will not be delivered.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the @link Handler#sendMessage(Message) method will return false.
* </p><p>
* If the thread has not been started or has finished (that is if
* @link #getLooper returns null), then false is returned.
* Otherwise the looper is asked to quit and true is returned.
* </p>
*
* @return True if the looper looper has been asked to quit or false if the
* thread had not yet started running.
*/
public boolean quitSafely()
Looper looper = getLooper();
if (looper != null)
looper.quitSafely();
return true;
return false;
/**
* Returns the identifier of this thread. See Process.myTid().
*/
public int getThreadId()
return mTid;
可以看出,定义一个HandlerThread对象需要new出来,
public HandlerThread(String name)
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT;
/**
* Constructs a HandlerThread.
* @param name
* @param priority The priority to run the thread at. The value supplied must be from
* @link android.os.Process and not from java.lang.Thread.
*/
public HandlerThread(String name, int priority)
super(name);
mPriority = priority;
因为它本身是一个Thread,所以如果要该线程跑起来,需要手动调用start()方法,当调用start方法的时候就会执行Thread的run()方法,
@Override
public void run()
mTid = Process.myTid();
Looper.prepare();
synchronized (this)
mLooper = Looper.myLooper();
notifyAll();
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
可以看到内部调用了Looper.prepare()方法和Loop.loop()方法,在调用Looper.loop()方法之前调用了一个空的实现方法:onLooperPrepared(),我们可以实现自己的onLooperPrepared()方法,做一些Looper的初始化操作;run方法里面当mLooper创建完成后有个notifyAll(),getLooper()中有个wait(),这是为什么呢?因为的mLooper在一个线程中执行,而我们的handler是在UI线程初始化的,也就是说,我们必须等到mLooper创建完成,才能正确的返回getLooper();wait(),notify()就是为了解决这两个线程的同步问题
/**
* This method returns the Looper associated with this thread. If this thread not been started
* or for any reason is isAlive() returns false, this method will return null. If this thread
* has been started, this method will block until the looper has been initialized.
* @return The looper.
*/
public Looper getLooper()
if (!isAlive())
return null;
// If the thread has been started, wait until the looper has been created.
synchronized (this)
while (isAlive() && mLooper == null)
try
wait();
catch (InterruptedException e)
return mLooper;
HandlerThread的使用可以参考IntentService的使用。
使用场景:
HandlerThread 所做的就是在新开的子线程中创建了 Looper,那它的使用场景就是 Thread + Looper 使用场景的结合,即:在子线程中执行耗时的、可能有多个任务的操作。
总结:
1.HandlerThread本质上是一个Thread,内部创建了该线程的Looper,
2.HandlerThread我们不但可以实现UI线程与子线程的通信同样也可以实现子线程与子线程之间的通信。
以上是关于Android HandlerThread的主要内容,如果未能解决你的问题,请参考以下文章