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.google.android.apps.watchme.StreamerActivity.java

private void setupCamera(int width, int height) {
    CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    try {/*w ww . j  a  v a 2  s .  c o m*/
        for (String cameraIDs : cameraManager.getCameraIdList()) {
            CameraCharacteristics cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraIDs);
            if (cameraCharacteristics
                    .get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT) {
                continue;
            }
            StreamConfigurationMap map = cameraCharacteristics
                    .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
            //@edsonAndrade
            // Alike the camera api version of the app, I am forcing the app into the landscape mode
            int deviceOrientation = getWindowManager().getDefaultDisplay().getRotation();
            int totalRotation = sensorToDeeviceRotation(cameraCharacteristics, deviceOrientation);
            boolean swapRotation = totalRotation == 90 || totalRotation == 270;
            int rotatedWidth = width;
            int rotatedHeight = height;
            if (swapRotation) {
                rotatedHeight = width;
                rotatedWidth = height;
            }
            previewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), rotatedWidth,
                    rotatedHeight);
            cameraId = cameraIDs;
            return;
        }
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

From source file:com.raulh82vlc.face_detection_sample.camera2.presentation.FDCamera2Presenter.java

private void createCameraPreview() {
    if (isViewAvailable()) {
        try {/*www  .  ja  v  a 2 s .  co m*/
            SurfaceTexture texture = activityView.getTextureView().getSurfaceTexture();
            assert texture != null;

            texture.setDefaultBufferSize(imageDimension.getWidth(), imageDimension.getHeight());
            Surface surface = new Surface(texture);
            captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            captureRequestBuilder.addTarget(surface);
            cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {
                @Override
                public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                    //The camera is already closed
                    if (null == cameraDevice) {
                        return;
                    }
                    // When the session is ready, we start displaying the preview.
                    cameraCaptureSessions = cameraCaptureSession;
                    updatePreview();
                }

                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
                    //                Toast.makeText(this, "Configuration change", Toast.LENGTH_SHORT).show();
                }
            }, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.google.android.apps.watchme.StreamerActivity.java

void startPreview() {
    SurfaceTexture surfaceTexture = textureView.getSurfaceTexture();
    surfaceTexture.setDefaultBufferSize(previewSize.getWidth(), previewSize.getHeight());
    Surface previewSurface = new Surface(surfaceTexture);
    try {//from ww  w .j  a  v a  2  s .c om
        captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        captureRequestBuilder.addTarget(previewSurface);

        cameraDevice.createCaptureSession(Arrays.asList(previewSurface),
                new CameraCaptureSession.StateCallback() {
                    @Override
                    public void onConfigured(@NonNull CameraCaptureSession session) {
                        try {
                            session.setRepeatingRequest(captureRequestBuilder.build(), null, backgroundHandler);
                        } catch (CameraAccessException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onConfigureFailed(@NonNull CameraCaptureSession session) {
                        Toast.makeText(getApplicationContext(), "The preview failed to setup",
                                Toast.LENGTH_SHORT).show();
                    }
                }, null);

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

From source file:com.raulh82vlc.face_detection_sample.camera2.presentation.FDCamera2Presenter.java

private void openCamera(int width, int height) {
    if (isViewAvailable()) {
        if (ActivityCompat.checkSelfPermission(activityView,
                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(activityView,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activityView,
                    new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE },
                    FDCamera2Activity.PERMISSIONS_REQUEST_CAMERA);
            return;
        }/*from   w w w  . j a  v  a 2 s .c  om*/
        setUpCameraOutputs(width, height);
        configureTransform(previewSize.getHeight(), previewSize.getWidth());
        // Add permission for camera and let user grant the permission
        CameraManager manager = (CameraManager) activityView.getSystemService(Context.CAMERA_SERVICE);

        try {
            if (!cameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
                throw new RuntimeException("Time out waiting to lock camera opening.");
            }
            String[] cameras = manager.getCameraIdList();
            String cameraId = cameras[1];
            //                CameraCharacteristics characteristics
            //                        = manager.getCameraCharacteristics(cameraId);
            // Check detectModes
            //                int[] faceDetectModes = characteristics.get(CameraCharacteristics.STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES);
            manager.openCamera(cameraId, stateCallback, mainThread.get());
        } catch (CameraAccessException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
        }
    }
}

From source file:com.example.android.mediarecorder.MainActivity.java

private boolean preparePreview() {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
        try {//from  w  ww .j a v a 2s. c o m
            CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
            String id = manager.getCameraIdList()[0];
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(id);
            sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        } catch (CameraAccessException e) {
            Log.e("ERROR", "Cannot access Camera2 API");
            e.printStackTrace();
        }
    }

    Log.i(TAG, "Preparing Camera Preview");
    // BEGIN_INCLUDE (configure_preview)
    //        mCamera = CameraHelper.getDefaultCameraInstance();

    // We need to make sure that our preview and recording video size are supported by the
    // camera. Query camera to find all the sizes and choose the optimal size given the
    // dimensions of our preview surface.
    Camera.Parameters parameters = mCamera.getParameters();
    List<Camera.Size> mSupportedPreviewSizes = parameters.getSupportedPreviewSizes();
    List<Camera.Size> mSupportedVideoSizes = parameters.getSupportedVideoSizes();
    Camera.Size optimalSize = CameraHelper.getOptimalVideoSize(mSupportedVideoSizes, mSupportedPreviewSizes,
            mPreview.getWidth(), mPreview.getHeight());

    // Use the same size for recording profile.
    CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
    profile.videoFrameWidth = optimalSize.width;
    profile.videoFrameHeight = optimalSize.height;

    // likewise for the camera object itself.
    parameters.setPreviewSize(profile.videoFrameWidth, profile.videoFrameHeight);
    mCamera.setParameters(parameters);
    try {
        // Requires API level 11+, For backward compatibility use {@link setPreviewDisplay}
        // with {@link SurfaceView}
        //                mCamera.setPreviewTexture(mPreview.getSurfaceTexture());

        mHolder = mPreview.getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        //            mHolder.setKeepScreenOn(true);

        setCameraDisplayOrientation(0);
        mCamera.setPreviewDisplay(mPreview.getHolder());
        mCamera.startPreview();
        Log.i(TAG, "Setting Preview Display");
    } catch (IOException e) {
        Log.e(TAG, "Surface texture is unavailable or unsuitable" + e.getMessage());
        return false;
    }
    // END_INCLUDE (configure_preview)
    return true;
}

From source file:com.raulh82vlc.face_detection_sample.camera2.presentation.FDCamera2Presenter.java

/**
 * Sets up member variables related to camera.
 *
 * @param width  The width of available size for camera preview
 * @param height The height of available size for camera preview
 *///w  w w .ja va2 s  .c o  m
private void setUpCameraOutputs(int width, int height) {
    if (isViewAvailable()) {
        CameraManager manager = (CameraManager) activityView.getSystemService(Context.CAMERA_SERVICE);
        try {
            for (String cameraId : manager.getCameraIdList()) {
                CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);

                // We don't use a front facing camera in this sample.
                Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
                if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
                    continue;
                }

                StreamConfigurationMap map = characteristics
                        .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                if (map == null) {
                    continue;
                }

                imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];

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

                Point displaySize = new Point();
                activityView.getWindowManager().getDefaultDisplay().getSize(displaySize);
                int rotatedPreviewWidth = width;
                int rotatedPreviewHeight = height;
                int maxPreviewWidth = displaySize.x;
                int maxPreviewHeight = displaySize.y;

                if (maxPreviewWidth > MAX_PREVIEW_WIDTH) {
                    maxPreviewWidth = MAX_PREVIEW_WIDTH;
                }

                if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) {
                    maxPreviewHeight = MAX_PREVIEW_HEIGHT;
                }

                // Danger, W.R.! Attempting to use too large a preview size could  exceed the camera
                // bus' bandwidth limitation, resulting in gorgeous previews but the storage of
                // garbage capture data.
                previewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), rotatedPreviewWidth,
                        rotatedPreviewHeight, maxPreviewWidth, maxPreviewHeight, largest);

                // We fit the aspect ratio of TextureView to the size of preview we picked.
                int orientation = activityView.getResources().getConfiguration().orientation;
                if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    activityView.getTextureView().setAspectRatio(previewSize.getWidth(),
                            previewSize.getHeight());
                } else {
                    activityView.getTextureView().setAspectRatio(previewSize.getHeight(),
                            previewSize.getWidth());
                }
                return;
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            // Currently an NPE is thrown when the Camera2API is used but not supported on the
            // device this code runs.
        }
    }
}

From source file:wisc.drivesense.vediorecorder.CameraFragment.java

public void startRecordingVideo() {
    Log.d(TAG, "startRecordingVideo()");
    if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
        return;/*from   w ww. ja v  a2  s  .  com*/
    }
    try {
        closePreviewSession();
        setUpMediaRecorder();
        SurfaceTexture texture = mTextureView.getSurfaceTexture();
        assert texture != null;
        texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
        List<Surface> surfaces = new ArrayList<>();

        // Set up Surface for the camera preview
        Surface previewSurface = new Surface(texture);
        surfaces.add(previewSurface);
        mPreviewBuilder.addTarget(previewSurface);

        // Set up Surface for the MediaRecorder
        mRecorderSurface = mMediaRecorder.getSurface();
        surfaces.add(mRecorderSurface);
        mPreviewBuilder.addTarget(mRecorderSurface);

        // Start a capture session
        // Once the session starts, we can update the UI and start recording
        mCameraDevice.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() {

            @Override
            public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                mPreviewSession = cameraCaptureSession;
                updatePreview();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // Start recording
                        mMediaRecorder.start();
                    }
                });
            }

            @Override
            public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
                Activity activity = getActivity();
                if (null != activity) {
                    Toast.makeText(activity, "Failed", Toast.LENGTH_SHORT).show();
                }
            }
        }, mBackgroundHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }

}

From source file:com.example.testcamera.Camera2BasicFragmentEasy.java

/**
 * Opens the camera specified by {@link Camera2BasicFragmentEasy#mCameraId}.
 */// w w  w  .  j  a  va  2s  . c  om
private void openCamera(int width, int height) {
    if (ContextCompat.checkSelfPermission(getActivity(),
            Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        FragmentCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA }, 1);
        return;
    }

    mCameraId = setUpCameraOutputs(width, height);

    //        configureTransform(width, height);

    //        ?CameraId???CameraIdCamera?CameraDevice
    Activity activity = getActivity();
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
        if (!mSemaphore.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
            throw new RuntimeException("Time out waiting to lock camera opening.");
        }
        //            ??CameraId
        //            ?CameraDeviceStateCallback??CameraDevice
        //            ?Handler?null?
        manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
    }
}

From source file:com.example.camera2apidemo.Camera2Fragment.java

private void unlockFocus() {
    try {//from  ww w  .ja v  a 2s.  c o  m
        mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_CANCEL);

        mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE,
                CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);

        mCaptureSession.capture(mPreviewRequestBuilder.build(), null, mBackgroundHandler);
        // After this, the camera will go back to the normal state of preview.
        mState = STATE_PREVIEW;
        mCaptureSession.setRepeatingRequest(mPreviewRequest, null, mBackgroundHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

From source file:com.example.camera2apidemo.Camera2Fragment.java

private void startPrieview() {
    try {//from   w  w w .  j av  a 2 s. c o m
        mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        mPreviewRequestBuilder.addTarget(surface);

        mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
        mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE,
                CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
        mPreviewRequest = mPreviewRequestBuilder.build();

        mCaptureSession.setRepeatingRequest(mPreviewRequest, null, null);

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