首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > Android >

Android中HandlerThread种的解析

2012-09-01 
Android中HandlerThread类的解析Android应用中的消息循环由Looper和Handler配合完成,Looper类用于封装消息

Android中HandlerThread类的解析

Android应用中的消息循环由Looper和Handler配合完成,Looper类用于封装消息循环,类中有个MessageQueue消息队列;Handler类封装了消息投递和消息处理等功能。

系统默认情况下只有主线程(即UI线程)绑定Looper对象,因此在主线程中可以直接创建Handler的实例,但是在子线程中就不能直接new出Handler的实例了,因为子线程默认并没有Looper对象,此时会抛出RuntimeException异常:

Android中HandlerThread种的解析

浏览下Handler的默认构造函数就一目了然了:

/** * 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 {private int mPriority; // 线程优先级private int mTid = -1; // 线程IDprivate Looper mLooper; // 我们需要的Looper对象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;}/** * 在Looper.loop()之前执行动作的回调函数 */protected void onLooperPrepared() {}public void run() {mTid = Process.myTid();Looper.prepare(); // 创建本线程的Looper对象synchronized (this) {mLooper = Looper.myLooper();notifyAll(); //通知所有等待该线程Looper对象的其他子线程,本线程的Looper对象已就绪}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(); //Looper对象未创建好,等待} catch (InterruptedException e) {}}}return mLooper;}/** * Ask the currently running looper to quit. 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. */public boolean quit() {Looper looper = getLooper();if (looper != null) {looper.quit();return true;}return false;}/** * Returns the identifier of this thread. See Process.myTid(). */public int getThreadId() {return mTid;}}



2楼zhyl8157121昨天 12:57
同问,这种黑底的怎么弄的
Re: ACE1985昨天 12:57
回复zhyl8157121http://download.csdn.net/download/liubo060807/1831716 如果需要更改eclipse背景主题的话,上面这个主题还可以
1楼fengqiangfeng昨天 08:59
楼主的eclipse皮肤是哪一种,求指导
Re: ACE1985昨天 12:45
回复fengqiangfeng详情请咨询CSDN

热点排行