Android video app setup background thread

The android video app setup background thread tutorial describes how to create an android handler and thread for that handler.

It is important to setup a background handler to remove time consuming tasks from the main UI thread.

Many of the api’s provided by android camera2 provide support for a background thread handler. So it’s recommended to provide a background thread handler if supported.

This android tutorial will be describing how to create a background thread handler.

Get Code

The code to start this tutorial is on github here

https://github.com/mobapptuts/android_camera2_api_video_app.git Tag camera2-video-back-thread

or you can run this command

git clone https://github.com/mobapptuts/android_camera2_api_video_app.git –branch camera2-video-back-thread

Steps

Setup the background handler

Create two activity members, one for the handler and one for the thread

private HandlerThread mBackgroundHandlerThread;
private Handler mBackgroundHandler;

 Create start & stop background thread methods

  private void startBackgroundThread() {
        mBackgroundHandlerThread = new HandlerThread("Camera2VideoImage");
        mBackgroundHandlerThread.start();
        mBackgroundHandler = new Handler(mBackgroundHandlerThread.getLooper());
    }

    private void stopBackgroundThread() {
        mBackgroundHandlerThread.quitSafely();
        try {
            mBackgroundHandlerThread.join();
            mBackgroundHandlerThread = null;
            mBackgroundHandler = null;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

Add the start & stop background thread methods to the android activity onResume & onPause methods

 @Override
    protected void onResume() {
        super.onResume();

        startBackgroundThread();

        if(mTextureView.isAvailable()) {
            setupCamera(mTextureView.getWidth(), mTextureView.getHeight());
        } else {
            mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
        }
    }

    @Override
    protected void onPause() {
        closeCamera();

        stopBackgroundThread();

        super.onPause();
    }

Android video app setup background thread Summary

In this android tutorial we learned the importance of removing time consuming tasks from the main UI thread by provided a background thread handler.

And also learned how to create an android thread and it’s handler as well as the procedure for cleaning up the thread when it is no longer needed.

About The Author
-

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>