Example usage for android.hardware.camera2 CameraAccessException printStackTrace

List of usage examples for android.hardware.camera2 CameraAccessException printStackTrace

Introduction

In this page you can find the example usage for android.hardware.camera2 CameraAccessException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.example.aschere.cdhprototype2.Camera2RawFragment.java

/**
 * Opens the camera specified by {@link #mCameraId}.
 *///ww  w.  j  a va2 s .  c o  m
private void openCamera() {
    if (!setUpCameraOutputs()) {
        return;
    }

    try {
        // Wait for any previously running session to finish.
        if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
            Log.e(TAG, "Time out waiting to lock camera opening.");
            //throw new RuntimeException("Time out waiting to lock camera opening.");
        }

        String cameraId;
        Handler backgroundHandler;
        synchronized (mCameraStateLock) {
            cameraId = mCameraId;
            backgroundHandler = mBackgroundHandler;
        }

        // Attempt to open the camera. mStateCallback will be called on the background handler's
        // thread when this succeeds or fails.

        if (ActivityCompat.checkSelfPermission(appContext,
                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //Android Studio won't shut up about permissions
            ;
        }
        manager.openCamera(cameraId, mStateCallback, backgroundHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
    }
}

From source file:com.example.aschere.cdhprototype2.Camera2RawFragment.java

/**
 * Send a capture request to the camera device that initiates a capture targeting the JPEG and
 * RAW outputs.//from w ww .  j ava 2  s. co  m
 * <p/>
 * Call this only with {@link #mCameraStateLock} held.
 */
private void captureStillPictureLocked() {
    try {
        if (null == mCameraDevice) {
            return;
        }
        // This is the CaptureRequest.Builder that we use to take a picture.
        final CaptureRequest.Builder captureBuilder = mCameraDevice
                .createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);

        captureBuilder.addTarget(mJpegImageReader.get().getSurface());
        captureBuilder.addTarget(mRawImageReader.get().getSurface());

        // Use the same AE and AF modes as the preview.
        setup3AControlsLocked(captureBuilder);

        // Set orientation.
        int rotation = Surface.ROTATION_0;
        captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, sensorToDeviceRotation(mCharacteristics, rotation));

        // Set request tag to easily track results in callbacks.
        captureBuilder.setTag(mRequestCounter.getAndIncrement());

        CaptureRequest request = captureBuilder.build();

        // Create an ImageSaverBuilder in which to collect results, and add it to the queue
        // of active requests.
        ImageSaver.ImageSaverBuilder jpegBuilder = new ImageSaver.ImageSaverBuilder(appContext)
                .setCharacteristics(mCharacteristics);
        ImageSaver.ImageSaverBuilder rawBuilder = new ImageSaver.ImageSaverBuilder(appContext)
                .setCharacteristics(mCharacteristics);

        mJpegResultQueue.put((int) request.getTag(), jpegBuilder);
        mRawResultQueue.put((int) request.getTag(), rawBuilder);

        mCaptureSession.capture(request, mCaptureCallback, mBackgroundHandler);

    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

From source file:com.example.camera2raw.Camera2RawFragment.java

/**
 * Send a capture request to the camera device that initiates a capture targeting the JPEG and
 * RAW outputs.//from   w  w  w  . j  av a2  s  .  com
 * <p/>
 * Call this only with {@link #mCameraStateLock} held.
 */
private void captureStillPictureLocked() {
    try {
        final Activity activity = getActivity();
        if (null == activity || null == mCameraDevice) {
            return;
        }
        // This is the CaptureRequest.Builder that we use to take a picture.
        final CaptureRequest.Builder captureBuilder = mCameraDevice
                .createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);

        captureBuilder.addTarget(mJpegImageReader.get().getSurface());
        captureBuilder.addTarget(mRawImageReader.get().getSurface());

        // Use the same AE and AF modes as the preview.
        setup3AControlsLocked(captureBuilder);

        // Set orientation.
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, sensorToDeviceRotation(mCharacteristics, rotation));

        // Set request tag to easily track results in callbacks.
        captureBuilder.setTag(mRequestCounter.getAndIncrement());

        CaptureRequest request = captureBuilder.build();

        // Create an ImageSaverBuilder in which to collect results, and add it to the queue
        // of active requests.
        ImageSaverBuilder jpegBuilder = new ImageSaverBuilder(activity).setCharacteristics(mCharacteristics);
        ImageSaverBuilder rawBuilder = new ImageSaverBuilder(activity).setCharacteristics(mCharacteristics);

        mJpegResultQueue.put((int) request.getTag(), jpegBuilder);
        mRawResultQueue.put((int) request.getTag(), rawBuilder);

        mCaptureSession.capture(request, mCaptureCallback, mBackgroundHandler);

    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

From source file:com.example.aschere.cdhprototype2.Camera2RawFragment.java

/**
 * Initiate a still image capture.//from  w  ww  .j a  v a  2 s.  co m
 * <p/>
 * This function sends a capture request that initiates a pre-capture sequence in our state
 * machine that waits for auto-focus to finish, ending in a "locked" state where the lens is no
 * longer moving, waits for auto-exposure to choose a good exposure value, and waits for
 * auto-white-balance to converge.
 */
public String takePicture() {
    synchronized (mCameraStateLock) {
        mPendingUserCaptures++;

        Log.i("fragmentTakePicture", "Take Picture called!");
        // If we already triggered a pre-capture sequence, or are in a state where we cannot
        // do this, return immediately.
        /*if (mState != STATE_PREVIEW) {
           Log.w(TAG, "return immediately");
        return null;
        }*/
        setUpCameraOutputs();
        openCamera();
        startBackgroundThread();

        try {
            Log.i(TAG, "inside try");

            if (mPreviewRequestBuilder == null) {
                Log.i(TAG, "Have to create preview request builder");
                if (mCameraDevice == null) {
                    Log.w(TAG, "Camera device not opened?");
                    setUpCameraOutputs();
                    openCamera();
                }
                createCameraPreviewSessionLocked();
            }
            // Update state machine to wait for auto-focus, auto-exposure, and
            // auto-white-balance (aka. "3A") to converge.
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
                    CameraMetadata.CONTROL_AF_TRIGGER_START);
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
                    CameraMetadata.CONTROL_AE_PRECAPTURE_TRIGGER_START);
            mState = STATE_WAITING_FOR_3A_CONVERGENCE;

            // Start a timer for the pre-capture sequence.
            startTimerLocked();

            // Replace the existing repeating request with one with updated 3A triggers.
            mCaptureSession.capture(mPreviewRequestBuilder.build(), mPreCaptureCallback, mBackgroundHandler);
            //closeCamera();
            int count = 0;
            while (!imageReturnable) {
                count++;
            }
            Log.i(TAG, "Image acquired!" + count);
            imageReturnable = false;
            return imageToReturn;
        } catch (CameraAccessException e) {
            e.printStackTrace();
        } finally {
            closeCamera();
        }
        return null;
    }
}

From source file:com.example.aschere.cdhprototype2.Camera2RawFragment.java

/**
 * Sets up state related to camera that is needed before opening a {@link CameraDevice}.
 *///  w w  w. j a  v  a 2 s.  co  m
private boolean setUpCameraOutputs() {
    if (manager == null) {
        //ErrorDialog.buildErrorDialog("This device doesn't support Camera2 API.").show(getFragmentManager(), "dialog");
        Log.e(TAG, "This device doesn't support Camera2 API.");
        return false;
    }
    try {
        // Find a CameraDevice that supports RAW captures, and configure state.
        for (String cameraId : manager.getCameraIdList()) {
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);

            // We only use a camera that supports RAW in this sample.
            if (!contains(characteristics.get(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES),
                    CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_RAW)) {
                continue;
            }

            StreamConfigurationMap map = characteristics
                    .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);

            // For still image captures, we use the largest available size.
            Size largestJpeg = Collections.max(Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
                    new CompareSizesByArea());

            Size largestRaw = Collections.max(Arrays.asList(map.getOutputSizes(ImageFormat.RAW_SENSOR)),
                    new CompareSizesByArea());

            synchronized (mCameraStateLock) {
                // Set up ImageReaders for JPEG and RAW outputs.  Place these in a reference
                // counted wrapper to ensure they are only closed when all background tasks
                // using them are finished.
                if (mJpegImageReader == null || mJpegImageReader.getAndRetain() == null) {
                    mJpegImageReader = new RefCountedAutoCloseable<>(ImageReader.newInstance(
                            largestJpeg.getWidth(), largestJpeg.getHeight(), ImageFormat.JPEG, /*maxImages*/5));
                }
                mJpegImageReader.get().setOnImageAvailableListener(mOnJpegImageAvailableListener,
                        mBackgroundHandler);

                if (mRawImageReader == null || mRawImageReader.getAndRetain() == null) {
                    mRawImageReader = new RefCountedAutoCloseable<>(
                            ImageReader.newInstance(largestRaw.getWidth(), largestRaw.getHeight(),
                                    ImageFormat.RAW_SENSOR, /*maxImages*/ 5));
                }
                mRawImageReader.get().setOnImageAvailableListener(mOnRawImageAvailableListener,
                        mBackgroundHandler);

                mCharacteristics = characteristics;
                mCameraId = cameraId;
            }
            Log.i(TAG, "setUpCameraOutputs successful");
            return true;
        }
    } catch (CameraAccessException e) {
        Log.e(TAG, "setUpCameraOutputs stacktraced");
        e.printStackTrace();
    }

    // If we found no suitable cameras for capturing RAW, warn the user.
    //ErrorDialog.buildErrorDialog("This device doesn't support capturing RAW photos").show(getFragmentManager(), "dialog");
    Log.e(TAG, "This device doesn't support capturing RAW photos");
    return false;
}

From source file:com.ape.camera2raw.Camera2RawFragment.java

/**
 * Called after a RAW/JPEG capture has completed; resets the AF trigger state for the
 * pre-capture sequence./*from   w  ww  .j  a va2  s .c  o  m*/
 * <p/>
 * Call this only with {@link #mCameraStateLock} held.
 */
private void finishedCaptureLocked() {
    try {
        // Reset the auto-focus trigger in case AF didn't run quickly enough.
        if (!mNoAFRun) {
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
                    CameraMetadata.CONTROL_AF_TRIGGER_CANCEL);

            mCaptureSession.capture(mPreviewRequestBuilder.build(), mPreCaptureCallback, mBackgroundHandler);

            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
                    CameraMetadata.CONTROL_AF_TRIGGER_IDLE);
        }
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

From source file:com.quectel.camera2test.Camera2RawFragment.java

/**
 * Opens the camera specified by {@link #mCameraId}.
 *///from   w  ww .j  av  a  2  s.c  o m
@SuppressWarnings("MissingPermission")
private void openCamera() {
    if (!setUpCameraOutputs()) {
        return;
    }
    if (!hasAllPermissionsGranted()) {
        requestCameraPermissions();
        return;
    }

    Activity activity = getActivity();
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
        // Wait for any previously running session to finish.
        if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
            throw new RuntimeException("Time out waiting to lock camera opening.");
        }

        String cameraId;
        Handler backgroundHandler;
        synchronized (mCameraStateLock) {
            cameraId = mCameraId;
            backgroundHandler = mBackgroundHandler;
        }

        // Attempt to open the camera. mStateCallback will be called on the background handler's
        // thread when this succeeds or fails.
        manager.openCamera(cameraId, mStateCallback, backgroundHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
    }
}

From source file:com.ape.camera2raw.Camera2RawFragment.java

/**
 * Opens the camera specified by {@link #mCameraId}.
 *//*from w  w  w . ja v  a2 s.co m*/
private void openCamera() {
    if (!setUpCameraOutputs()) {
        return;
    }
    if (!hasAllPermissionsGranted()) {
        requestCameraPermissions();
        return;
    }

    Activity activity = getActivity();
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
        // Wait for any previously running session to finish.
        if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
            throw new RuntimeException("Time out waiting to lock camera opening.");
        }

        String cameraId;
        Handler backgroundHandler;
        synchronized (mCameraStateLock) {
            cameraId = mCameraId;
            backgroundHandler = mBackgroundHandler;
        }

        // Attempt to open the camera. mStateCallback will be called on the background handler's
        // thread when this succeeds or fails.
        manager.openCamera(cameraId, mStateCallback, backgroundHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
    }
}

From source file:com.ape.camera2raw.Camera2RawFragment.java

/**
 * Send a capture request to the camera device that initiates a capture targeting the JPEG and
 * RAW outputs./*from w ww.j  ava  2 s.com*/
 * <p/>
 * Call this only with {@link #mCameraStateLock} held.
 */
private void captureStillPictureLocked() {
    try {
        final Activity activity = getActivity();
        if (null == activity || null == mCameraDevice) {
            return;
        }
        // This is the CaptureRequest.Builder that we use to take a picture.
        final CaptureRequest.Builder captureBuilder = mCameraDevice
                .createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);

        captureBuilder.addTarget(mJpegImageReader.get().getSurface());
        captureBuilder.addTarget(mRawImageReader.get().getSurface());

        // Use the same AE and AF modes as the preview.
        setup3AControlsLocked(captureBuilder);

        // Set orientation.
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, sensorToDeviceRotation(mCharacteristics, rotation));

        // Set request tag to easily track results in callbacks.
        captureBuilder.setTag(mRequestCounter.getAndIncrement());

        CaptureRequest request = captureBuilder.build();

        // Create an ImageSaverBuilder in which to collect results, and add it to the queue
        // of active requests.
        ImageSaver.ImageSaverBuilder jpegBuilder = new ImageSaver.ImageSaverBuilder(activity)
                .setCharacteristics(mCharacteristics);
        ImageSaver.ImageSaverBuilder rawBuilder = new ImageSaver.ImageSaverBuilder(activity)
                .setCharacteristics(mCharacteristics);

        mJpegResultQueue.put((int) request.getTag(), jpegBuilder);
        mRawResultQueue.put((int) request.getTag(), rawBuilder);

        mCaptureSession.capture(request, mCaptureCallback, mBackgroundHandler);

    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

From source file:com.example.android.camera2raw.Camera2RawFragment.java

/**
 * Sets up state related to camera that is needed before opening a {@link CameraDevice}.
 *//*from  w  w  w  .  j  a  va  2s  . com*/
private boolean setUpCameraOutputs() {
    Activity activity = getActivity();
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    if (manager == null) {
        ErrorDialog.buildErrorDialog("This device doesn't support Camera2 API.").show(getFragmentManager(),
                "dialog");
        return false;
    }
    try {
        // Find a CameraDevice that supports RAW captures, and configure state.
        for (String cameraId : manager.getCameraIdList()) {
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);

            // We only use a camera that supports RAW in this sample.
            if (!contains(characteristics.get(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES),
                    CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_RAW)) {
                continue;
            }

            StreamConfigurationMap map = characteristics
                    .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);

            // For still image captures, we use the largest available size.
            Size largestJpeg = Collections.max(Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
                    new CompareSizesByArea());

            Size largestRaw = Collections.max(Arrays.asList(map.getOutputSizes(ImageFormat.RAW_SENSOR)),
                    new CompareSizesByArea());

            synchronized (mCameraStateLock) {
                // Set up ImageReaders for JPEG and RAW outputs.  Place these in a reference
                // counted wrapper to ensure they are only closed when all background tasks
                // using them are finished.
                if (mJpegImageReader == null || mJpegImageReader.getAndRetain() == null) {
                    mJpegImageReader = new RefCountedAutoCloseable<>(ImageReader.newInstance(
                            largestJpeg.getWidth(), largestJpeg.getHeight(), ImageFormat.JPEG, /*maxImages*/5));
                }
                mJpegImageReader.get().setOnImageAvailableListener(mOnJpegImageAvailableListener,
                        mBackgroundHandler);

                if (mRawImageReader == null || mRawImageReader.getAndRetain() == null) {
                    mRawImageReader = new RefCountedAutoCloseable<>(
                            ImageReader.newInstance(largestRaw.getWidth(), largestRaw.getHeight(),
                                    ImageFormat.RAW_SENSOR, /*maxImages*/ 5));
                }
                mRawImageReader.get().setOnImageAvailableListener(mOnRawImageAvailableListener,
                        mBackgroundHandler);

                mCharacteristics = characteristics;
                mCameraId = cameraId;
            }
            return true;
        }
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }

    // If we found no suitable cameras for capturing RAW, warn the user.
    ErrorDialog.buildErrorDialog("This device doesn't support capturing RAW photos").show(getFragmentManager(),
            "dialog");
    return false;
}