`
shhero
  • 浏览: 3382 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
社区版块
存档分类
最新评论

线程 handler looper

阅读更多

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()方法即可

 

 

 

1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics