---
title: "线程 handler looper"
author: "shhero"
date: "2012-01-11T15:09:19Z"
tags: []
categories: ["移动开发"]
slug: "handler-looper"
draft: false
lastmod: "2012-01-16T12:17:27Z"
id: 1341384
url: "https://itb.iteye.com/blog/1341384"
---

0，Handler对象必须依赖Looper才能工作，Handler使用的是哪个线程的Looper，handleMessage()方法就在哪个线程执行。（顺便说明：Handler的post和sendMessage方法本质上是一样的，使用同一个队列，可以去参见源码）

 

1，主线程默认拥有Looper，因此可以直接使用Handler。

2，子线程默认没有Looper，要想在子线程中使用Handler，典型例子如下：

```
 class LooperThread extends Thread {
      public Handler mHandler;

      public void run() {
          Looper.prepare();

          mHandler = new Handler() {
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
      }
  }
```

 3，HandlerThread继承自Thread，带有Looper。

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.

典型用法如下：

```
HandlerThread handlerthread=new HandlerThread("线程名");
		handlerthread.start();//start方法必须先调用，否则handlerthread的Looper将为null,可参见sdk源码
		Handler handler= new Handler(handlerthread.getLooper()){
			@Override
			public void handleMessage(Message msg) {
				System.out.println("Thread("+Thread.currentThread().getId()+","+Thread.currentThread().getName());
			}
		};
```

  HandlerThread主要是在Thread的基础上增加了一个Looper对象，HandlerThread一旦start后不会自行结束，当要做的事完成之后我们应该将其结束并释放Looper以避免无谓的系统资源浪费，调用HandlerThread.quit()方法即可