HandlerThread的简单使用

2017-07-01  本文已影响0人  ironman_

HandlerThread里会有一个自己的looper,不需要我们去管理他的状态
但是我们还是需要手动去调用一下start。

可以通过HandlerThread.getLooper来创建handler,从而给这个ThreadHandler发送消息。

主要代码片段:

handlerThread = new HandlerThread("autoFocus");
handlerThread.start();
handler = new Handler(handlerThread.getLooper(), this);

caution:一定要等到handlerThread start之后才可以去通过他的looper创建handler,否则会有问题。
这里创建了一个HandlerThread,然后启动了他,再创建了一个能发送消息到这个线程的handler,这时候我们就可以往这个线程里丢东西了。

这里有一个自动循环对焦的HandlerThread的实现:

final class AutoFocusManager implements Camera.AutoFocusCallback , Handler.Callback{

   private static final String TAG = AutoFocusManager.class.getSimpleName();
   private static final int MSG_AUTO_FOCUS = 123;

   private static final long AUTO_FOCUS_INTERVAL_MS = 1000L;

   private boolean active;
   private final Camera camera;
   private Handler handler;
   private HandlerThread handlerThread;

   AutoFocusManager(Context context, Camera camera) {
      this.camera = camera;
      handlerThread = new HandlerThread("autoFocus");
      handlerThread.start();
      handler = new Handler(handlerThread.getLooper(), this);
      start();
   }

   @Override
   public boolean handleMessage(Message msg) {
      if (msg != null) {
         switch (msg.what) {
            case MSG_AUTO_FOCUS:
               requestFocus();
               break;
         }
      }
      return false;
   }

   private void requestFocus() {
      if (active) {
         try {
            camera.autoFocus(this);
         } catch (RuntimeException re) {
            QLog.e(re);
         }
      }
   }

   @SuppressWarnings("unchecked")
   @SuppressLint("NewApi")
   @Override
   public synchronized void onAutoFocus(boolean success, Camera theCamera) {
      if (success) {
         QLog.e("autofocus", "auto focus success");
      } else {
         QLog.e("autofocus", "auto focus fail");
      }
      if (active) {
         handler.sendEmptyMessageDelayed(MSG_AUTO_FOCUS, AUTO_FOCUS_INTERVAL_MS);
      }
   }

   private void start() {
      active = true;
      handler.sendEmptyMessage(MSG_AUTO_FOCUS);
   }

   synchronized void stop() {
      try {
         camera.cancelAutoFocus();
      } catch (RuntimeException re) {
         QLog.e(TAG, "Unexpected exception while cancelling focusing", re);
      }
      active = false;
      if (handlerThread != null) {
         handlerThread.quit();
      }
   }
}
上一篇下一篇

猜你喜欢

热点阅读