Example usage for android.hardware Camera open

List of usage examples for android.hardware Camera open

Introduction

In this page you can find the example usage for android.hardware Camera open.

Prototype

public static Camera open(int cameraId) 

Source Link

Document

Creates a new Camera object to access a particular hardware camera.

Usage

From source file:com.example.leon.article.Activity.video.videorecord.CameraActivity.java

public void onResume() {
    super.onResume();
    if (!hasCamera(getApplicationContext())) {
        //???/*from   w  w  w  . j a  v  a  2  s . com*/
        Toast.makeText(getApplicationContext(), R.string.dont_have_camera_error, Toast.LENGTH_SHORT).show();
        setResult(UpVideoActivity.RESULT_CODE_FOR_RECORD_VIDEO_FAILED);
        releaseCamera();
        releaseMediaRecorder();
        finish();
    }
    if (mCamera == null) {
        releaseCamera();
        final boolean frontal = cameraFront;

        int cameraId = findFrontFacingCamera();
        if (cameraId < 0) {
            //???
            switchCameraListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(CameraActivity.this, R.string.dont_have_front_camera, Toast.LENGTH_SHORT)
                            .show();
                }
            };

            //???
            cameraId = findBackFacingCamera();
            if (flash) {
                mPreview.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                mBinding.buttonFlash.setImageResource(R.mipmap.ic_flash_on_white);
            }
        } else if (!frontal) {
            cameraId = findBackFacingCamera();
            if (flash) {
                mPreview.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                mBinding.buttonFlash.setImageResource(R.mipmap.ic_flash_on_white);
            }
        }

        mCamera = Camera.open(cameraId);
        mPreview.refreshCamera(mCamera);
        reloadQualities(cameraId);

    }
}

From source file:com.grayraven.barcoder.CameraActivityFragement.java

private boolean safeCameraOpen() {
    boolean qOpened = false;

    try {//from w  w w  .  j  a  v a  2  s.c  o  m
        stopPreviewAndFreeCamera();

        //get index of front camera
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        int count = Camera.getNumberOfCameras();
        for (int i = 0; i < count; i++) {
            Camera.getCameraInfo(i, cameraInfo);
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
                mCamera = Camera.open(i);
                mCameraId = i;
                break;
            }
        }
        qOpened = (mCamera != null);
    } catch (Exception e) {
        Log.e(getString(R.string.app_name), "failed to open Camera");
        e.printStackTrace();
    }

    return qOpened;
}

From source file:org.artoolkit.ar.base.camera.CaptureCameraPreview.java

private void openCamera(SurfaceHolder surfaceHolderInstance, int cameraIndex) {
    Log.i(TAG, "openCamera(): called");
    try {//from   ww w  .j  a  v  a  2s .co  m
        camera = Camera.open(cameraIndex);
    } catch (RuntimeException ex) {
        Log.e(TAG, "openCamera(): RuntimeException caught, " + ex.getMessage() + ", abnormal exit");
        return;
    }
    //catch (CameraAccessException ex) {
    //      Log.e(TAG, "openCamera(): CameraAccessException caught, " + ex.getMessage() + ", abnormal exit");
    //      return;
    //  }
    catch (Exception ex) {
        Log.e(TAG, "openCamera()): exception caught, " + ex.getMessage() + ", abnormal exit");
        return;
    }

    if (!SetOrientationAndPreview(surfaceHolderInstance, cameraIndex)) {
        Log.e(TAG, "openCamera(): call to SetOrientationAndPreview() failed, openCamera() failed");
    } else
        Log.i(TAG, "openCamera(): succeeded");
}

From source file:com.ezartech.ezar.flashlight.Flashlight.java

private void updateLight(int newLightState, final CallbackContext callbackContext) {
    Camera releaseableCamera = null;// ww w  . j a v a 2s . c o  m

    try {
        lightState = newLightState;

        if (localPreviewCamera == null) {
            localPreviewCamera = Camera.open(cameraId);
        }
        Parameters parameters;
        parameters = localPreviewCamera.getParameters();
        parameters.setFlashMode(
                newLightState == LIGHT_ON ? Parameters.FLASH_MODE_TORCH : Parameters.FLASH_MODE_OFF);
        localPreviewCamera.setParameters(parameters);

        if (localPreviewCamera != null) {
            if (newLightState == LIGHT_ON) {
                try {
                    localPreviewCamera.startPreview();
                    if (hiddenSurfaceTexture == null) {
                        hiddenSurfaceTexture = new SurfaceTexture(0);
                    }
                    localPreviewCamera.setPreviewTexture(hiddenSurfaceTexture);
                } catch (Exception ex) {
                    callbackContext.error("Unable to start light.");
                }
            } else {
                localPreviewCamera.stopPreview();
                releaseableCamera = localPreviewCamera;
                localPreviewCamera = null;
            }
        }

    } finally {
        if (releaseableCamera != null) {
            releaseableCamera.release();
        }
    }

    if (callbackContext != null) {
        callbackContext.success();
    }
}

From source file:com.prt.thirdeye.CamManager.java

/**
 * Opens the camera and show its preview in the preview
 * //from  w  w w  . j  a va  2  s.  c  o  m
 * @param cameraId
 *            The facing of the camera
 * @return true if the operation succeeded, false otherwise
 */
@SuppressLint("NewApi")
public boolean open(final int cameraId) {
    if (mCamera != null) {
        if (mPreviewPauseListener != null) {
            mPreviewPauseListener.onPreviewPause();
        }

        // Close the previous camera
        releaseCamera();
    }

    mCameraReady = false;

    // Try to open the camera
    new Thread() {
        public void run() {
            try {
                if (mCamera != null) {
                    Log.e(TAG, "Previous camera not closed! Not opening");
                    return;
                }

                mCamera = Camera.open(cameraId);
                Log.v(TAG, "Camera is open");

                if (Build.VERSION.SDK_INT >= 17) {
                    mCamera.enableShutterSound(false);
                }
                mCamera.setPreviewCallback(mPreview);
                mCurrentFacing = cameraId;
                mParameters = mCamera.getParameters();

                if (DEBUG_LOG_PARAMS) {
                    String params = mCamera.getParameters().flatten();
                    final int step = params.length() > 256 ? 256 : params.length();
                    for (int i = 0; i < params.length(); i += step) {
                        Log.d(TAG, params);
                        params = params.substring(step);
                    }
                }

                // Mako hack to raise FPS
                if (Build.DEVICE.equals("mako")) {
                    Camera.Size maxSize = mParameters.getSupportedPictureSizes().get(0);
                    mParameters.setPictureSize(maxSize.width, maxSize.height);
                }

                if (mAutoFocusMoveCallback != null) {
                    setAutoFocusMoveCallback(mAutoFocusMoveCallback);
                }
            } catch (Exception e) {
                Log.e(TAG, "Error while opening cameras: " + e.getMessage(), e);

                if (mCameraReadyListener != null) {
                    mCameraReadyListener.onCameraFailed();
                }

                return;
            }

            // Update the preview surface holder with the new opened camera
            mPreview.notifyCameraChanged(false);

            if (mCameraReadyListener != null) {
                mCameraReadyListener.onCameraReady();
            }
            if (mPreviewPauseListener != null) {
                mPreviewPauseListener.onPreviewResume();
            }

            mPreview.setPauseCopyFrame(false);

            mCameraReady = true;
        }
    }.start();

    return true;
}

From source file:com.pimp.companionforband.fragments.extras.CameraActivity.java

void CameraSwitch(ImageButton cameraSwitch) {
    Camera.Parameters params;//from w w  w  .ja  v  a2s  . c o  m

    int cameraId = -1;
    switch (cameraSwitch.getContentDescription().toString()) {
    case "to Rear":
        cameraId = findFrontFacingCamera(true);
        cameraSwitch.setImageResource(R.drawable.ic_camera_rear_white_48dp);
        cameraSwitch.setContentDescription("to Front");
        break;
    case "to Front":
        cameraId = findFrontFacingCamera(false);
        cameraSwitch.setImageResource(R.drawable.ic_camera_front_white_48dp);
        cameraSwitch.setContentDescription("to Rear");
        break;
    }
    if (cameraId < 0) {
        Toast.makeText(this, "Camera not found.", Toast.LENGTH_LONG).show();
        return;
    } else {
        surfaceDestroyed(surfaceHolder);
        camera = Camera.open(cameraId);
    }

    params = camera.getParameters();

    List<Camera.Size> sizes = params.getSupportedPictureSizes();
    Camera.Size size = sizes.get(0);
    for (int i = 0; i < sizes.size(); i++) {
        if (sizes.get(i).width > size.width)
            size = sizes.get(i);
    }
    params.setPictureSize(size.width, size.height);
    camera.setParameters(params);

    try {
        camera.setPreviewDisplay(surfaceHolder);
        camera.startPreview();
        cameraSwitch.setImageResource(R.drawable.ic_camera_rear_white_48dp);
    } catch (Exception e) {
        System.err.println(e);
    }
}

From source file:com.androchill.call411.MainActivity.java

private Phone getHardwareSpecs() {
    ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    PhoneBuilder pb = new PhoneBuilder();
    pb.setModelNumber(Build.MODEL);/*from  ww w .  j  a v  a  2 s . c  om*/
    pb.setManufacturer(Build.MANUFACTURER);

    Process p = null;
    String board_platform = "No data available";
    try {
        p = new ProcessBuilder("/system/bin/getprop", "ro.chipname").redirectErrorStream(true).start();
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = "";
        while ((line = br.readLine()) != null) {
            board_platform = line;
        }
        p.destroy();
    } catch (IOException e) {
        e.printStackTrace();
        board_platform = "No data available";
    }

    pb.setProcessor(board_platform);
    ActivityManager.MemoryInfo mInfo = new ActivityManager.MemoryInfo();
    activityManager.getMemoryInfo(mInfo);
    pb.setRam((int) (mInfo.totalMem / 1048576L));
    pb.setBatteryCapacity(getBatteryCapacity());
    pb.setTalkTime(-1);
    pb.setDimensions("No data available");

    WindowManager mWindowManager = getWindowManager();
    Display mDisplay = mWindowManager.getDefaultDisplay();
    Point mPoint = new Point();
    mDisplay.getSize(mPoint);
    pb.setScreenResolution(mPoint.x + " x " + mPoint.y + " pixels");

    DisplayMetrics mDisplayMetrics = new DisplayMetrics();
    mDisplay.getMetrics(mDisplayMetrics);
    int mDensity = mDisplayMetrics.densityDpi;
    pb.setScreenSize(
            Math.sqrt(Math.pow(mPoint.x / (double) mDensity, 2) + Math.pow(mPoint.y / (double) mDensity, 2)));

    Camera camera = Camera.open(0);
    android.hardware.Camera.Parameters params = camera.getParameters();
    List sizes = params.getSupportedPictureSizes();
    Camera.Size result = null;

    ArrayList<Integer> arrayListForWidth = new ArrayList<Integer>();
    ArrayList<Integer> arrayListForHeight = new ArrayList<Integer>();

    for (int i = 0; i < sizes.size(); i++) {
        result = (Camera.Size) sizes.get(i);
        arrayListForWidth.add(result.width);
        arrayListForHeight.add(result.height);
    }
    if (arrayListForWidth.size() != 0 && arrayListForHeight.size() != 0) {
        pb.setCameraMegapixels(
                Collections.max(arrayListForHeight) * Collections.max(arrayListForWidth) / (double) 1000000);
    } else {
        pb.setCameraMegapixels(-1);
    }
    camera.release();

    pb.setPrice(-1);
    pb.setWeight(-1);
    pb.setSystem("Android " + Build.VERSION.RELEASE);

    StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
    StatFs statInternal = new StatFs(Environment.getRootDirectory().getAbsolutePath());
    double storageSize = ((stat.getBlockSizeLong() * stat.getBlockCountLong())
            + (statInternal.getBlockSizeLong() * statInternal.getBlockCountLong())) / 1073741824L;
    pb.setStorageOptions(storageSize + " GB");
    TelephonyManager telephonyManager = ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE));
    String operatorName = telephonyManager.getNetworkOperatorName();
    if (operatorName.length() == 0)
        operatorName = "No data available";
    pb.setCarrier(operatorName);
    pb.setNetworkFrequencies("No data available");
    pb.setImage(null);
    return pb.createPhone();
}

From source file:com.ktouch.kdc.launcher4.camera.CameraManager.java

/**
 * Opens the camera and show its preview in the preview
 *
 * @param cameraId The facing of the camera
 * @return true if the operation succeeded, false otherwise
 *///from  w  w w .j  ava 2s  .c o m
public boolean open(final int cameraId) {
    if (mCamera != null) {
        if (mPreviewPauseListener != null) {
            mPreviewPauseListener.onPreviewPause();
        }

        // Close the previous camera
        releaseCamera();
    }

    mCameraReady = false;

    // Try to open the camera
    new Thread() {
        public void run() {
            try {
                if (DEBUG_PROFILER)
                    Profiler.getDefault().start("CameraOpen");
                if (mCamera != null) {
                    Log.e(TAG, "Previous camera not closed! Not opening");
                    return;
                }

                mCamera = Camera.open(cameraId);
                Log.v(TAG, "Camera is open");

                if (Build.VERSION.SDK_INT >= 17) {
                    mCamera.enableShutterSound(false);
                }
                mCamera.setPreviewCallback(mPreview);
                mCurrentFacing = cameraId;
                mParameters = mCamera.getParameters();

                if (DEBUG_LOG_PARAMS) {
                    String params = mCamera.getParameters().flatten();
                    final int step = params.length() > 256 ? 256 : params.length();
                    for (int i = 0; i < params.length(); i += step) {
                        Log.d(TAG, params);
                        params = params.substring(step);
                    }
                }

                // Mako hack to raise FPS
                if (Build.DEVICE.equals("mako")) {
                    Camera.Size maxSize = mParameters.getSupportedPictureSizes().get(0);
                    mParameters.setPictureSize(maxSize.width, maxSize.height);
                }

                if (mAutoFocusMoveCallback != null) {
                    setAutoFocusMoveCallback(mAutoFocusMoveCallback);
                }
            } catch (Exception e) {
                Log.e(TAG, "Error while opening cameras: " + e.getMessage(), e);

                if (mCameraReadyListener != null) {
                    mCameraReadyListener.onCameraFailed();
                }

                return;
            }

            // Update the preview surface holder with the new opened camera
            mPreview.notifyCameraChanged(false);

            if (mCameraReadyListener != null) {
                mCameraReadyListener.onCameraReady();
            }
            if (mPreviewPauseListener != null) {
                mPreviewPauseListener.onPreviewResume();
            }

            mPreview.setPauseCopyFrame(false);

            mCameraReady = true;
            if (DEBUG_PROFILER)
                Profiler.getDefault().logProfile("CameraOpen");
        }
    }.start();

    return true;
}

From source file:com.octopepper.mediapickerinstagram.commons.cameraview.api14.Camera1.java

private void openCamera() {
    if (mCamera != null) {
        releaseCamera();/*from   w w w . ja  v  a 2 s. c  o m*/
    }
    mCamera = Camera.open(mCameraId);
    mCameraParameters = mCamera.getParameters();
    // Supported preview sizes
    mPreviewSizes.clear();
    for (Camera.Size size : mCameraParameters.getSupportedPreviewSizes()) {
        mPreviewSizes.add(new Size(size.width, size.height));
    }
    // Supported picture sizes;
    mPictureSizes.clear();
    for (Camera.Size size : mCameraParameters.getSupportedPictureSizes()) {
        mPictureSizes.add(new Size(size.width, size.height));
    }
    // AspectRatio
    if (mAspectRatio == null) {
        mAspectRatio = Constants.DEFAULT_ASPECT_RATIO;
    }
    adjustCameraParameters();
    mCamera.setDisplayOrientation(calcCameraRotation(mDisplayOrientation));
    mCallback.onCameraOpened();
}

From source file:uk.ac.horizon.artcodes.camera.CameraView.java

private void openCamera(int cameraId) {
    Log.i("Scanner",
            "Device manufacturer: " + android.os.Build.MANUFACTURER + " model: " + android.os.Build.MODEL);

    camera = Camera.open(cameraId);
    Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
    Camera.getCameraInfo(cameraId, cameraInfo);

    Camera.Parameters parameters = camera.getParameters();
    List<String> focusModes = parameters.getSupportedFocusModes();
    if (//!android.os.Build.MANUFACTURER.equalsIgnoreCase("SAMSUNG") &&
    focusModes != null//  ww w. j  ava2 s. com
            && !(this.experience != null && this.experience.getRequestedAutoFocusMode() != null
                    && (this.experience.getRequestedAutoFocusMode().equals("tapToFocus")
                            || this.experience.getRequestedAutoFocusMode().equals("blurScore"))
                    && focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO))
            && focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
    } else if (focusModes != null && focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
        // if FOCUS_MODE_CONTINUOUS_VIDEO is not supported flag that manual auto-focus is needed every few seconds
        Log.w("Scanner", "Camera requires manual focusing");
        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
        if (!(this.experience.getRequestedAutoFocusMode() != null
                && this.experience.getRequestedAutoFocusMode().equals("blurScore"))) {
            deviceNeedsTapToFocus = true;
        }
    }

    float ratioOfSurface = (float) surfaceHeight / surfaceWidth;
    if (ratioOfSurface < 1) {
        ratioOfSurface = 1 / ratioOfSurface;
    }
    Log.i("Scanner",
            "Surface size: " + surfaceWidth + "x" + surfaceHeight + " (Ratio: " + ratioOfSurface + ")");
    Log.i("Scanner", "Format = " + parameters.getPictureFormat());

    // Step 2: Find scanner preview that is best match for estimated surface ratio
    final List<Camera.Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes();
    Camera.Size bestFitSoFar = null;
    float ratioDifferenceOfBestFitSoFar = 0;
    StringBuilder cameraPreviewSizeDebugMessage = new StringBuilder("Available camera preview sizes: ");
    for (Camera.Size supportedSize : supportedPreviewSizes) {
        float ratio = (float) supportedSize.width / supportedSize.height;
        float ratioDifference = Math.abs(ratio - ratioOfSurface);

        cameraPreviewSizeDebugMessage.append(supportedSize.width);
        cameraPreviewSizeDebugMessage.append('x');
        cameraPreviewSizeDebugMessage.append(supportedSize.height);
        cameraPreviewSizeDebugMessage.append(" (");
        cameraPreviewSizeDebugMessage.append(ratio);
        cameraPreviewSizeDebugMessage.append(") ");

        if (bestFitSoFar == null || ratioDifference < ratioDifferenceOfBestFitSoFar) {
            bestFitSoFar = supportedSize;
            ratioDifferenceOfBestFitSoFar = ratioDifference;
        }
    }
    Log.i("Scanner", cameraPreviewSizeDebugMessage.toString());

    if (bestFitSoFar != null) {
        // Would only be null if there are no supportedPreviewSizes
        this.debug_resolution = "Selected Preview Size: " + bestFitSoFar.width + "x" + bestFitSoFar.height
                + " (" + ((float) bestFitSoFar.width / (float) bestFitSoFar.height) + ")";
        Log.i("Scanner", this.debug_resolution);
        parameters.setPreviewSize(bestFitSoFar.width, bestFitSoFar.height);

        camera.setParameters(parameters);

        info = new CameraInfo(cameraInfo, parameters, getDeviceRotation());
        camera.setDisplayOrientation(info.getRotation());
        setDetector(detector, experience);

        try {
            camera.setPreviewDisplay(surface);
        } catch (IOException e) {
            Log.w("Scanner", e.getMessage(), e);
        }

        camera.startPreview();
    }
}