HandlerThread源码分析

HandlerThread(本质是Thread)
1.减轻主线程的压力,提高UI的流畅度
2.可以处理多个任务,开启一个线程起到多个线程的作用(looper共享)


public class HandlerThread extends Thread {
    int mPriority;
    Looper mLooper;

    public HandlerThread(String name) {
        super(name);
        mPriority = Process.THREAD_PRIORITY_DEFAULT;
    }

    public HandlerThread(String name, int priority) {
        super(name);
        mPriority = priority;
    }

    //run方法里面的的内容在子线程中执行
    public void run() {
        mTid = Process.myTid();
        Looper.prepare(); //创建Looper放到ThreadLocal里面
        synchronized (this) {
            //从ThreadLocal中获取当前子线程的Looper
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }
    
    /**
     * 如果Looper没有创建好,会阻塞在这里
     */
    public Looper getLooper() {
        synchronized (this) {
            while (isAlive() && mLooper == null) {
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
        }
        return mLooper;
    }

    public boolean quit() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quit();
            return true;
        }
        return false;
    }
}

HandlerThread与Camera的能够Looper共享

需求:
打开相机
预览回调(编码)

异步任务的Looper,使用的MainLooper

public class AsyncTaskActivity extends Activity
 implements Callback {
    
    static final String TAG = "AsyncTaskActivity";
    
    Camera mCamera;
    SurfaceView surfaceView;
    SurfaceHolder surfaceHolder;
    byte[] buffers;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler_thread2);
        
        surfaceView = (SurfaceView) findViewById(R.id.surface_view);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
    }
    
    class MyTask extends AsyncTask implements PreviewCallback{

        @Override
        protected Void doInBackground(Void... params) {
            //子线程中打开
            Log.d(TAG, Thread.currentThread().getName() + "_open");
            mCamera = Camera.open(CameraInfo.CAMERA_FACING_BACK);
            try {
                mCamera.setPreviewDisplay(surfaceHolder);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Camera.Parameters parameters = mCamera.getParameters();
            //设置相机参数
            parameters.setPreviewSize(480, 320); //预览画面宽高
            mCamera.setParameters(parameters);
            //获取预览图像数据
            buffers = new byte[480 * 320 * 4];
            mCamera.addCallbackBuffer(buffers);
            mCamera.setPreviewCallbackWithBuffer(this);
            mCamera.startPreview();
            
            Log.d(TAG, Thread.currentThread().getName()+ "_doInBackground");
            
            return null;
        }

        //画面预览的回调
        @Override
        public void onPreviewFrame(byte[] data, Camera camera) {
            if(mCamera != null){
                mCamera.addCallbackBuffer(buffers);
                //主线程执行
                Log.d(TAG, Thread.currentThread().getName()+ "_onPreviewFrame");
            }
        }
        
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        new MyTask().execute();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, 
int width, int height) {
        
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        
    }

}

onPreviewFrame方法的回调实在相机类(Camera)里面的EventHandler.handleMessage方法中执行,onPreviewFrame方法调用跟EventHandler.handleMessage在同一个线程里面,而EventHandler.handleMessage调用所在线程是由Looper所在线程决定。
由于在上面的代码中没有调用Looper.prepare(), 结合Camera的构造函数可以知道会进入else if这个条件里面,此时Looper是在主线程的,因此上面代码中的onPreviewFrame方法在主线程调用的。

Camera(int cameraId) {
    ...
    Looper looper;
    //Looper.myLooper()不为空前提是调用了Looper.prepare()方法
    if ((looper = Looper.myLooper()) != null) {
        mEventHandler = new EventHandler(this, looper);
    } else if ((looper = Looper.getMainLooper()) != null) {//主线程
        mEventHandler = new EventHandler(this, looper);
    } else {
        mEventHandler = null;
    }
}

public class HandlerThreadActivity2 extends Activity implements Callback {

    static final String TAG = "jason";
    
    Camera mCamera;
    SurfaceView surfaceView;
    SurfaceHolder surfaceHolder;
    byte[] buffers;
    
    HandlerThread mHandlerThread = new HandlerThread("my_handlerthread");
    Handler subHandler;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler_thread2);
        
        surfaceView = (SurfaceView) findViewById(R.id.surface_view);
        surfaceHolder = surfaceView.getHolder();
        
        surfaceHolder.addCallback(this);
    }
    
    class MyTask implements Runnable, PreviewCallback{

        @Override
        public void run() {
            //打开相机
            //子线程中打开
            Log.d("jason", Thread.currentThread().getName() + "_open");
            mCamera = Camera.open(CameraInfo.CAMERA_FACING_BACK);
            try {
                mCamera.setPreviewDisplay(surfaceHolder);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Camera.Parameters parameters = mCamera.getParameters();
            //设置相机参数
            parameters.setPreviewSize(480, 320); //预览画面宽高
            mCamera.setParameters(parameters);
            //获取预览图像数据
            buffers = new byte[480 * 320 * 4];
            mCamera.addCallbackBuffer(buffers);
            mCamera.setPreviewCallbackWithBuffer(this);
            mCamera.startPreview();
            
            Log.d(TAG, Thread.currentThread().getName()+ "_run");
        }
        
        @Override
        public void onPreviewFrame(byte[] data, Camera camera) {
            if(mCamera != null){
                mCamera.addCallbackBuffer(buffers);
                //子线程执行
                Log.d(TAG, Thread.currentThread().getName()+ "_onPreviewFrame");
            }
        }
        
    }
    

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        mHandlerThread.start();
        subHandler = new Handler(mHandlerThread.getLooper());
        subHandler.post(new MyTask());
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, 
int width, int height) {
        
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        
    }
}


你可能感兴趣的:(HandlerThread源码分析)