Example usage for android.hardware Camera release

List of usage examples for android.hardware Camera release

Introduction

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

Prototype

public final void release() 

Source Link

Document

Disconnects and releases the Camera object resources.

Usage

From source file:org.akvo.caddisfly.util.ApiUtil.java

public static boolean isCameraInUse(Context context, @Nullable final Activity activity) {
    Camera camera = null;
    try {/*from w  ww  . j  av  a2 s  .com*/
        camera = CameraHelper.getCamera(context, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(@NonNull DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                if (activity != null) {
                    activity.finish();
                }
            }
        });

    } catch (Exception ignored) {
    }

    if (camera != null) {
        camera.release();
        return false;
    }

    return true;
}

From source file:org.webrtc.videoengine.VideoCaptureDeviceInfoAndroid.java

private static String getDeviceInfo() {
    try {//from   w  ww.ja  va  2s .c  om
        JSONArray devices = new JSONArray();
        for (int i = 0; i < Camera.getNumberOfCameras(); ++i) {
            CameraInfo info = new CameraInfo();
            Camera.getCameraInfo(i, info);
            String uniqueName = deviceUniqueName(i, info);
            JSONObject cameraDict = new JSONObject();
            devices.put(cameraDict);
            List<Size> supportedSizes;
            List<int[]> supportedFpsRanges;
            Camera camera = null;
            try {
                camera = Camera.open(i);
                Parameters parameters = camera.getParameters();
                supportedSizes = parameters.getSupportedPreviewSizes();
                supportedFpsRanges = parameters.getSupportedPreviewFpsRange();
                Log.d(TAG, uniqueName);
            } catch (RuntimeException e) {
                Log.e(TAG, "Failed to open " + uniqueName + ", skipping", e);
                continue;
            } finally {
                if (camera != null) {
                    camera.release();
                }
            }

            JSONArray sizes = new JSONArray();
            for (Size supportedSize : supportedSizes) {
                JSONObject size = new JSONObject();
                size.put("width", supportedSize.width);
                size.put("height", supportedSize.height);
                sizes.put(size);
            }

            JSONArray mfpsRanges = new JSONArray();
            for (int[] range : supportedFpsRanges) {
                JSONObject mfpsRange = new JSONObject();
                // Android SDK deals in integral "milliframes per second"
                // (i.e. fps*1000, instead of floating-point frames-per-second) so we
                // preserve that through the Java->C++->Java round-trip.
                mfpsRange.put("min_mfps", range[Parameters.PREVIEW_FPS_MIN_INDEX]);
                mfpsRange.put("max_mfps", range[Parameters.PREVIEW_FPS_MAX_INDEX]);
                mfpsRanges.put(mfpsRange);
            }

            cameraDict.put("name", uniqueName);
            cameraDict.put("front_facing", isFrontFacing(info)).put("orientation", info.orientation)
                    .put("sizes", sizes).put("mfpsRanges", mfpsRanges);
        }
        String ret = devices.toString(2);
        Log.d(TAG, ret);
        return ret;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.fallahpoor.infocenter.fragments.CameraFragment.java

private void releaseCamera(Camera camera) {

    if (camera != null) {
        camera.release();
    }

}

From source file:com.bilibili.boxing.utils.CameraPickerHelper.java

/**
 * start system camera to take a picture
 *
 * @param activity      not null if fragment is null.
 * @param fragment      not null if activity is null.
 * @param subFolderPath a folder in external DCIM,must start with "/".
 *///from  ww  w.  ja va2s  . c  om
public void startCamera(final Activity activity, final Fragment fragment, final String subFolderPath) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || !takePhotoSecure(activity, fragment, subFolderPath)) {
        FutureTask<Boolean> task = BoxingExecutor.getInstance().runWorker(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                try {
                    // try...try...try
                    Camera camera = Camera.open();
                    camera.release();
                } catch (Exception e) {
                    BoxingLog.d("camera is not available.");
                    return false;
                }
                return true;
            }
        });
        try {
            if (task != null && task.get()) {
                startCameraIntent(activity, fragment, subFolderPath, MediaStore.ACTION_IMAGE_CAPTURE,
                        REQ_CODE_CAMERA);
            } else {
                callbackError();
            }
        } catch (InterruptedException | ExecutionException ignore) {
            callbackError();
        }

    }
}

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  w  ww  .  jav  a2  s  .com
    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.ezartech.ezar.videooverlay.ezAR.java

private void init(JSONArray args, final CallbackContext callbackContext) {
    this.callbackContext = callbackContext;

    supportSnapshot = getSnapshotPlugin() != null;

    if (args != null) {
        String rgb = DEFAULT_RGB;
        try {/*from   www . j a v  a 2  s. c o  m*/
            rgb = args.getString(0);
        } catch (JSONException e) {
            //do nothing; resort to DEFAULT_RGB
        }

        setBackgroundColor(Color.parseColor(rgb));
        cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webViewView.setBackgroundColor(getBackgroundColor());
            }
        });
    }

    if (!PermissionHelper.hasPermission(this, permissions[0])) {
        PermissionHelper.requestPermission(this, CAMERA_SEC, Manifest.permission.CAMERA);
        return;
    }

    JSONObject jsonObject = new JSONObject();
    try {
        Display display = activity.getWindowManager().getDefaultDisplay();
        DisplayMetrics m = new DisplayMetrics();
        display.getMetrics(m);

        jsonObject.put("displayWidth", m.widthPixels);
        jsonObject.put("displayHeight", m.heightPixels);

        int mNumberOfCameras = Camera.getNumberOfCameras();
        Log.d(TAG, "Cameras:" + mNumberOfCameras);

        // Find the ID of the back-facing ("default") camera
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        for (int i = 0; i < mNumberOfCameras; i++) {
            Camera.getCameraInfo(i, cameraInfo);

            Parameters parameters;
            Camera open = null;
            try {
                open = Camera.open(i);
                parameters = open.getParameters();
            } finally {
                if (open != null) {
                    open.release();
                }
            }

            Log.d(TAG, "Camera facing:" + cameraInfo.facing);

            CameraDirection type = null;
            for (CameraDirection f : CameraDirection.values()) {
                if (f.getDirection() == cameraInfo.facing) {
                    type = f;
                }
            }

            if (type != null) {
                double zoom = 0;
                double maxZoom = 0;
                if (parameters.isZoomSupported()) {
                    maxZoom = (parameters.getMaxZoom() + 1) / 10.0;
                    zoom = Math.min(parameters.getZoom() / 10.0 + 1, maxZoom);
                }

                JSONObject jsonCamera = new JSONObject();
                jsonCamera.put("id", i);
                jsonCamera.put("position", type.toString());
                jsonCamera.put("zoom", zoom);
                jsonCamera.put("maxZoom", maxZoom);
                jsonObject.put(type.toString(), jsonCamera);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "Can't set exception", e);
    }

    callbackContext.success(jsonObject);
}

From source file:org.akvo.caddisfly.ui.activity.MainActivity.java

private boolean checkCameraFlash() {
    boolean hasFlash = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
    Camera camera = getCameraInstance();
    try {//from w w  w.j a v  a 2s  .  c o  m
        Camera.Parameters p;

        if (hasFlash) {
            p = camera.getParameters();
            if (p.getSupportedFlashModes() == null) {
                hasFlash = false;
            } else {
                if (p.getSupportedFlashModes().size() == 1) {
                    if (p.getSupportedFlashModes().get(0).equals("off")) {
                        hasFlash = false;
                    }
                }
            }
        }
    } finally {
        if (camera != null) {
            camera.release();
        }
    }
    return hasFlash;
}

From source file:com.googlecode.android_scripting.facade.CameraFacade.java

@Rpc(description = "Take a picture and save it to the specified path.", returns = "A map of Booleans autoFocus and takePicture where True "
        + "indicates success. cameraId also included.")
public Bundle cameraCapturePicture(@RpcParameter(name = "targetPath") final String targetPath,
        @RpcParameter(name = "useAutoFocus") @RpcDefault("true") Boolean useAutoFocus,
        @RpcParameter(name = "cameraId", description = "Id of camera to use. SDK 9") @RpcDefault("0") Integer cameraId)
        throws Exception {
    final BooleanResult autoFocusResult = new BooleanResult();
    final BooleanResult takePictureResult = new BooleanResult();
    Camera camera = openCamera(cameraId);
    if (camera == null) {
        String msg = String.format("can't initialize camera id %d, try to use another id", cameraId);
        Log.e(msg);/*from  www .ja  v a 2 s  .  co  m*/

        Bundle result = new Bundle();
        result.putInt("cameraId", cameraId);
        result.putBoolean("autoFocus", false);
        result.putBoolean("takePicture", false);
        result.putString("reason", msg + ", see logcat for details");
        return result;
    }
    Parameters prm = camera.getParameters();
    camera.setParameters(prm);

    try {
        Method method = camera.getClass().getMethod("setDisplayOrientation", int.class);
        method.invoke(camera, 90);
    } catch (Exception e) {
        Log.e(e);
    }

    try {
        FutureActivityTask<SurfaceHolder> previewTask = setPreviewDisplay(camera);
        camera.startPreview();
        if (useAutoFocus) {
            autoFocus(autoFocusResult, camera);
        }
        takePicture(new File(targetPath), takePictureResult, camera);
        previewTask.finish();
    } catch (Exception e) {
        Log.e(e);
    } finally {
        camera.release();
    }

    Bundle result = new Bundle();
    result.putBoolean("autoFocus", autoFocusResult.mmResult);
    result.putBoolean("takePicture", takePictureResult.mmResult);
    result.putInt("cameraId", cameraId);
    return result;
}

From source file:ca.nehil.rter.streamingapp2.StreamingActivity.java

private Camera openCamera() {
    Camera cameraDevice = Camera.open();
    for (int i = 0; i < numberOfCameras && cameraDevice == null; i++) {
        Log.d(LOG_TAG, "opening camera #" + String.valueOf(i));
        cameraDevice = Camera.open(i);/*from  ww w. j av  a  2 s. co m*/
    }
    try {
        if (cameraDevice == null) {
            throw new Exception("No camera device found");
        }
    } catch (Exception e) {
        cameraDevice.release();
        Log.e(LOG_TAG, e.getMessage());
        e.printStackTrace();
    }
    return cameraDevice;
}

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

private void init(final CallbackContext callbackContext) {
    this.callbackContext = callbackContext;

    if (!PermissionHelper.hasPermission(this, permissions[0])) {
        PermissionHelper.requestPermission(this, CAMERA_SEC, Manifest.permission.CAMERA);
        return;/*from   w  ww .j a  v a  2  s.  com*/
    }

    JSONObject jsonResult = new JSONObject();

    try {
        jsonResult.put("back", false);

        int mNumberOfCameras = Camera.getNumberOfCameras();

        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        for (int id = 0; id < mNumberOfCameras; id++) {
            Camera.getCameraInfo(id, cameraInfo);

            if (cameraInfo.facing != CameraInfo.CAMERA_FACING_BACK) {
                continue;
            }

            Parameters parameters;
            Camera camera = null;
            Camera releasableCamera = null;
            try {

                try {
                    if (id != voCameraId) {
                        camera = Camera.open(id);
                    } else {
                        camera = voCamera;
                    }

                } catch (RuntimeException re) {
                    System.out.println("Failed to open CAMERA: " + id);
                    continue;
                }

                parameters = camera.getParameters();

                List<String> torchModes = parameters.getSupportedFlashModes();
                boolean hasLight = torchModes != null && torchModes.contains(Parameters.FLASH_MODE_TORCH);

                if (hasLight) {
                    String key = "back";
                    cameraId = id;
                    ;
                    jsonResult.put(key, true);
                }

                //determine if camera should be released
                if (id != voCameraId) {
                    releasableCamera = camera;
                }

            } finally {
                if (releasableCamera != null) {
                    releasableCamera.release();
                }
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Can't set exception", e);
        callbackContext.error("Unable to access Camera for light information.");
        return;
    }

    callbackContext.success(jsonResult);
}