Java Code Examples for android.hardware.Camera#release()

The following examples show how to use android.hardware.Camera#release() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CheckPermission.java    From EasyPhotos with Apache License 2.0 6 votes vote down vote up
public synchronized static boolean isCameraUse(int cameraID) {
    boolean canUse = true;
    Camera mCamera = null;
    try {
        mCamera = Camera.open(cameraID);
        // setParameters 是针对魅族MX5。MX5通过Camera.open()拿到的Camera对象不为null
        Camera.Parameters mParameters = mCamera.getParameters();
        mCamera.setParameters(mParameters);
    } catch (Exception e) {
        e.printStackTrace();
        canUse = false;
    } finally {
        if (mCamera != null) {
            mCamera.release();
        } else {
            canUse = false;
        }
        mCamera = null;
    }
    return canUse;
}
 
Example 2
Source File: CameraTester.java    From PermissionAgent with Apache License 2.0 6 votes vote down vote up
@Override
public boolean test() throws Throwable {
    Camera camera = null;
    try {
        camera = Camera.open();
        Camera.Parameters parameters = camera.getParameters();
        camera.setParameters(parameters);
        camera.setPreviewCallback(PREVIEW_CALLBACK);
        camera.startPreview();
        return true;
    } catch (Throwable e) {
        PackageManager packageManager = mContext.getPackageManager();
        return !packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA);
    } finally {
        if (camera != null) {
            camera.stopPreview();
            camera.setPreviewCallback(null);
            camera.release();
        }
    }
}
 
Example 3
Source File: CameraManager.java    From Android with MIT License 6 votes vote down vote up
/**
 * Set the camera to camera (turn off the old camera, turn on the new camera)
 *
 * @param mCamera
 */
public Camera setChangeParameters(Activity activity, Camera mCamera, SurfaceHolder viewHolder) {
    if (Camera.getNumberOfCameras() <= 1) {
        return null;
    }
    try {
        mCamera.stopPreview();
        mCamera.setPreviewCallback(null);
        mCamera.release();
        cameraPosition = cameraPosition == 1 ? 0 : 1;
        Camera mNewCamera = getCameraInstance(cameraPosition);
        setParametersCamera(activity, mNewCamera);
        mNewCamera.setPreviewDisplay(viewHolder);
        mNewCamera.startPreview();
        return mNewCamera;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 4
Source File: CheckPermission.java    From imsdk-android with MIT License 6 votes vote down vote up
public synchronized static boolean isCameraUseable(int cameraID) {
    boolean canUse = true;
    Camera mCamera = null;
    try {
        mCamera = Camera.open(cameraID);
        // setParameters 是针对魅族MX5。MX5通过Camera.open()拿到的Camera对象不为null
        Camera.Parameters mParameters = mCamera.getParameters();
        mCamera.setParameters(mParameters);
    } catch (Exception e) {
        e.printStackTrace();
        canUse = false;
    } finally {
        if (mCamera != null) {
            mCamera.release();
        } else {
            canUse = false;
        }
        mCamera = null;
    }
    return canUse;
}
 
Example 5
Source File: CheckPermission.java    From imsdk-android with MIT License 6 votes vote down vote up
public synchronized static boolean isCameraUseable(int cameraID) {
    boolean canUse = true;
    Camera mCamera = null;
    try {
        mCamera = Camera.open(cameraID);
        // setParameters 是针对魅族MX5。MX5通过Camera.open()拿到的Camera对象不为null
        Camera.Parameters mParameters = mCamera.getParameters();
        mCamera.setParameters(mParameters);
    } catch (Exception e) {
        e.printStackTrace();
        canUse = false;
    } finally {
        if (mCamera != null) {
            mCamera.release();
        } else {
            canUse = false;
        }
        mCamera = null;
    }
    return canUse;
}
 
Example 6
Source File: LegacyOneCameraManagerImpl.java    From Camera2 with Apache License 2.0 6 votes vote down vote up
public OneCameraCharacteristics computeCameraCharacteristics(CameraId key)
        throws OneCameraAccessException
{
    OneCameraCharacteristics characteristics;
    Camera camera = null;
    try
    {
        camera = Camera.open(key.getLegacyValue());
        Camera.Parameters cameraParameters = camera.getParameters();
        if (cameraParameters == null)
        {
            Log.e(TAG, "Camera object returned null parameters!");
            throw new OneCameraAccessException("API1 Camera.getParameters() returned null");
        }
        characteristics = new OneCameraCharacteristicsImpl(
                mCameraInfos[key.getLegacyValue()], cameraParameters);
    } finally
    {
        if (camera != null)
        {
            camera.release();
        }
    }

    return characteristics;
}
 
Example 7
Source File: PermissionUtil.java    From AlbumCameraRecorder with MIT License 6 votes vote down vote up
public synchronized static boolean isCameraUseable(int cameraID) {
    boolean canUse = true;
    Camera mCamera = null;
    try {
        mCamera = Camera.open(cameraID);
        // setParameters 是针对魅族MX5。MX5通过Camera.open()拿到的Camera对象不为null
        Camera.Parameters mParameters = mCamera.getParameters();
        mCamera.setParameters(mParameters);
    } catch (Exception e) {
        e.printStackTrace();
        canUse = false;
    } finally {
        if (mCamera != null) {
            mCamera.release();
        } else {
            canUse = false;
        }
    }
    return canUse;
}
 
Example 8
Source File: DoubleCameraActivity.java    From AndroidDemo with MIT License 5 votes vote down vote up
@Override
protected void onDestroy() {
    super.onDestroy();
    if (disposable != null && !disposable.isDisposed()) {
        disposable.dispose();
        disposable = null;
    }
    if (cameras.size() > 0) {
        for (Camera camera : cameras) {
            camera.release();
        }
    }
}
 
Example 9
Source File: PjCameraInfo.java    From pjsip-android with Apache License 2.0 5 votes vote down vote up
public static PjCameraInfo GetCameraInfo(int idx)
   {
if (idx < 0 || idx >= GetCameraCount())
    return null;

Camera cam;
try {
    cam = Camera.open(idx);
} catch (Exception e) {
    Log.d("IOException", e.getMessage());
    return null;
}

PjCameraInfo pjci = new PjCameraInfo();

Camera.CameraInfo ci = new Camera.CameraInfo();
Camera.getCameraInfo(idx, ci);

pjci.facing = ci.facing;
pjci.orient = ci.orientation;

Camera.Parameters param = cam.getParameters();
cam.release();
cam = null;

pjci.supportedFormat = IntegerListToIntArray(
			    param.getSupportedPreviewFormats());
pjci.supportedFps1000 = IntArrayListToIntArray(
			    param.getSupportedPreviewFpsRange());
pjci.supportedSize = CameraSizeListToIntArray(
			    param.getSupportedPreviewSizes());

return pjci;
   }
 
Example 10
Source File: CameraManager.java    From Camdroid with Apache License 2.0 5 votes vote down vote up
public static boolean isCameraSupported() {
    if (isCameraSupported != null) {
        return isCameraSupported;
    }

    Camera camera = openCamera(-1);
    if (camera == null) {
        isCameraSupported = Boolean.FALSE;
    } else {
        Camera.Parameters params = camera.getParameters();

        String focusMode = findSettableValue(
                params.getSupportedFocusModes(),
                DESIRED_FOCUS_MODES.toArray(new String[0]));

        Integer previewFormat = findSettableValue(
                params.getSupportedPreviewFormats(), ImageFormat.NV21);

        Integer pictureFormat = findSettableValue(
                params.getSupportedPictureFormats(), ImageFormat.JPEG);

        String whiteBalanceMode = findSettableValue(
                params.getSupportedWhiteBalance(),
                Camera.Parameters.WHITE_BALANCE_AUTO);

        List<Size> sizes = params.getSupportedPictureSizes();

        Size size = calculateCameraPictureSize(sizes);
        isCameraSupported = Boolean.valueOf(size != null
                && size.height >= DESIRED_MIN_HEIGHT && focusMode != null
                && whiteBalanceMode != null && pictureFormat != null
                && previewFormat != null);

        camera.release();
    }

    return isCameraSupported;
}
 
Example 11
Source File: CameraUtils5.java    From CSipSimple with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void Init(VideoCaptureDeviceInfoAndroid deviceInfoAndroid,
        List<AndroidVideoCaptureDevice> listToPopulate) throws SecurityException,
        IllegalArgumentException, NoSuchMethodException, ClassNotFoundException,
        IllegalAccessException, InvocationTargetException {

    Camera camera = null;
    // Prior to Android 2.3
    AndroidVideoCaptureDevice newDevice;
    Camera.Parameters parameters;

    newDevice = deviceInfoAndroid.new AndroidVideoCaptureDevice();
    camera = Camera.open();
    parameters = camera.getParameters();
    newDevice.deviceUniqueName = "Camera 1, Facing back";
    newDevice.orientation = 90;
    deviceInfoAndroid.AddDeviceInfo(newDevice, parameters);

    listToPopulate.add(newDevice);
    camera.release();
    camera = null;

    newDevice = deviceInfoAndroid.new AndroidVideoCaptureDevice();
    newDevice.deviceUniqueName = "Camera 2, Facing front";
    parameters = deviceInfoAndroid.SearchOldFrontFacingCameras(newDevice);
    if (parameters != null) {
        deviceInfoAndroid.AddDeviceInfo(newDevice, parameters);
        listToPopulate.add(newDevice);
    }
}
 
Example 12
Source File: CameraUtils9.java    From CSipSimple with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void Init(VideoCaptureDeviceInfoAndroid deviceInfoAndroid,
        List<AndroidVideoCaptureDevice> listToPopulate)
        throws SecurityException,
        IllegalArgumentException, NoSuchMethodException, ClassNotFoundException,
        IllegalAccessException, InvocationTargetException {

    Camera camera = null;

    // From Android 2.3 and onwards
    for (int i = 0; i < Camera.getNumberOfCameras(); ++i) {
        AndroidVideoCaptureDevice newDevice = deviceInfoAndroid.new AndroidVideoCaptureDevice();

        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(i, info);
        newDevice.index = i;
        newDevice.orientation = info.orientation;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
            newDevice.deviceUniqueName =
                    "Camera " + i + ", Facing back, Orientation " + info.orientation;
        }
        else {
            newDevice.deviceUniqueName =
                    "Camera " + i + ", Facing front, Orientation " + info.orientation;
            newDevice.frontCameraType = FrontFacingCameraType.Android23;
        }

        camera = Camera.open(i);
        Camera.Parameters parameters = camera.getParameters();
        deviceInfoAndroid.AddDeviceInfo(newDevice, parameters);
        camera.release();
        camera = null;
        listToPopulate.add(newDevice);
    }
}
 
Example 13
Source File: ColorPickerBaseActivity.java    From CameraColorPicker with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCancelled(Camera camera) {
    super.onCancelled(camera);
    if (camera != null) {
        camera.release();
    }
}
 
Example 14
Source File: CameraPictureSizesCacher.java    From Camera2 with Apache License 2.0 5 votes vote down vote up
/**
 * Return list of Sizes for provided cameraId.  Check first to see if we
 * have it in the cache for the current android.os.Build.
 * Note: This method calls Camera.open(), so the camera must be closed
 * before calling or null will be returned if sizes were not previously
 * cached.
 *
 * @param cameraId cameraID we would like sizes for.
 * @param context  valid android application context.
 * @return List of valid sizes, or null if the Camera can not be opened.
 */
public static List<Size> getSizesForCamera(int cameraId, Context context)
{
    Optional<List<Size>> cachedSizes = getCachedSizesForCamera(cameraId, context);
    if (cachedSizes.isPresent())
    {
        return cachedSizes.get();
    }

    // No cached value, so need to query Camera API.
    Camera thisCamera;
    try
    {
        thisCamera = Camera.open(cameraId);
    } catch (RuntimeException e)
    {
        // Camera open will fail if already open.
        return null;
    }
    if (thisCamera != null)
    {
        String key_build = PICTURE_SIZES_BUILD_KEY + cameraId;
        String key_sizes = PICTURE_SIZES_SIZES_KEY + cameraId;
        SharedPreferences defaultPrefs = PreferenceManager.getDefaultSharedPreferences(context);

        List<Size> sizes = Size.buildListFromCameraSizes(thisCamera.getParameters()
                .getSupportedPictureSizes());
        thisCamera.release();
        SharedPreferences.Editor editor = defaultPrefs.edit();
        editor.putString(key_build, Build.DISPLAY);
        editor.putString(key_sizes, Size.listToString(sizes));
        editor.apply();
        return sizes;
    }
    return null;
}
 
Example 15
Source File: PjCameraInfo.java    From africastalking-android with MIT License 5 votes vote down vote up
public static PjCameraInfo GetCameraInfo(int idx)
   {
if (idx < 0 || idx >= GetCameraCount())
    return null;

Camera cam;
try {
    cam = Camera.open(idx);
} catch (Exception e) {
    Log.d("IOException", e.getMessage());
    return null;
}

PjCameraInfo pjci = new PjCameraInfo();

Camera.CameraInfo ci = new Camera.CameraInfo();
Camera.getCameraInfo(idx, ci);

pjci.facing = ci.facing;
pjci.orient = ci.orientation;

Camera.Parameters param = cam.getParameters();
cam.release();
cam = null;

pjci.supportedFormat = IntegerListToIntArray(
			    param.getSupportedPreviewFormats());
pjci.supportedFps1000 = IntArrayListToIntArray(
			    param.getSupportedPreviewFpsRange());
pjci.supportedSize = CameraSizeListToIntArray(
			    param.getSupportedPreviewSizes());

return pjci;
   }
 
Example 16
Source File: PeepersPreferenceActivity.java    From peepers with Apache License 2.0 5 votes vote down vote up
private void setSizePreferences(final ListPreference sizePreference,
                                final ListPreference cameraPreference)
{
    final String cameraPreferenceValue = cameraPreference.getValue();
    final int cameraIndex;
    if (cameraPreferenceValue != null)
    {
        cameraIndex = Integer.parseInt(cameraPreferenceValue);
    } // if
    else
    {
        cameraIndex = 0;
    } // else
    final Camera camera = Camera.open(cameraIndex);
    final Camera.Parameters params = camera.getParameters();
    camera.release();

    final List<Camera.Size> supportedPreviewSizes = params.getSupportedPreviewSizes();
    CharSequence[] entries = new CharSequence[supportedPreviewSizes.size()];
    CharSequence[] entryValues = new CharSequence[supportedPreviewSizes.size()];
    for (int previewSizeIndex = 0; previewSizeIndex < supportedPreviewSizes.size();
         previewSizeIndex++)
    {
        Camera.Size supportedPreviewSize = supportedPreviewSizes.get(previewSizeIndex);
        entries[previewSizeIndex] = supportedPreviewSize.width + "x"
                                    + supportedPreviewSize.height;
        entryValues[previewSizeIndex] = String.valueOf(previewSizeIndex);
    } // for

    sizePreference.setEntries(entries);
    sizePreference.setEntryValues(entryValues);

}
 
Example 17
Source File: CameraManager.java    From StarBarcode with Apache License 2.0 5 votes vote down vote up
@Override
public void closeCamera() {
    stopPreview();
    try {
        if (isOpenCamera()) {
            Camera theCamera = mCamera.getCamera();
            theCamera.release();
            mCamera = null;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }


}
 
Example 18
Source File: CameraSource.java    From flutter_mobile_vision with MIT License 4 votes vote down vote up
public static List<Size> getSizesForCameraFacing(int facing) {
    List<Size> sizeList = new ArrayList<>();

    int cameraId = CameraSource.getIdForRequestedCamera(facing);

    if (cameraId == -1) {
        return sizeList;
    }

    // Briefly open the camera to obtain valid sizes
    Camera camera = Camera.open(cameraId);

    List<SizePair> sizePairList = CameraSource.generateValidPreviewSizeList(camera);

    for (SizePair sizePair : sizePairList) {
        sizeList.add(sizePair.previewSize());
    }

    camera.release();

    return sizeList;
}
 
Example 19
Source File: CameraStreamer.java    From peepers with Apache License 2.0 4 votes vote down vote up
private void startStreamingIfRunning() throws IOException
{
    // Throws RuntimeException if the camera is currently opened
    // by another application.
    final Camera camera = Camera.open(mCameraIndex);
    final Camera.Parameters params = camera.getParameters();

    final List<Camera.Size> supportedPreviewSizes = params.getSupportedPreviewSizes();
    final Camera.Size selectedPreviewSize = supportedPreviewSizes.get(mPreviewSizeIndex);
    params.setPreviewSize(selectedPreviewSize.width, selectedPreviewSize.height);

    if (mUseFlashLight)
    {
        params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
    } // if

    // Set Preview FPS range. The range with the greatest maximum
    // is returned first.
    final List<int[]> supportedPreviewFpsRanges = params.getSupportedPreviewFpsRange();
    // XXX: However sometimes it returns null. This is a known bug
    // https://code.google.com/p/android/issues/detail?id=6271
    // In which case, we just don't set it.
    if (supportedPreviewFpsRanges != null)
    {
        final int[] range = supportedPreviewFpsRanges.get(0);
        params.setPreviewFpsRange(range[Camera.Parameters.PREVIEW_FPS_MIN_INDEX],
                range[Camera.Parameters.PREVIEW_FPS_MAX_INDEX]);
        camera.setParameters(params);
    } // if

    // Set up preview callback
    mPreviewFormat = params.getPreviewFormat();
    final Camera.Size previewSize = params.getPreviewSize();
    mPreviewWidth = previewSize.width;
    mPreviewHeight = previewSize.height;
    final int BITS_PER_BYTE = 8;
    final int bytesPerPixel = ImageFormat.getBitsPerPixel(mPreviewFormat) / BITS_PER_BYTE;
    // XXX: According to the documentation the buffer size can be
    // calculated by width * height * bytesPerPixel. However, this
    // returned an error saying it was too small. It always needed
    // to be exactly 1.5 times larger.
    mPreviewBufferSize = mPreviewWidth * mPreviewHeight * bytesPerPixel * 3 / 2 + 1;
    camera.addCallbackBuffer(new byte[mPreviewBufferSize]);
    mPreviewRect = new Rect(0, 0, mPreviewWidth, mPreviewHeight);
    camera.setPreviewCallbackWithBuffer(mPreviewCallback);

    // We assumed that the compressed image will be no bigger than
    // the uncompressed image.
    mJpegOutputStream = new MemoryOutputStream(mPreviewBufferSize);

    final MJpegHttpStreamer streamer = new MJpegHttpStreamer(mPort, mPreviewBufferSize);
    streamer.start();

    synchronized (mLock)
    {
        if (!mRunning)
        {
            streamer.stop();
            camera.release();
            return;
        } // if

        try
        {
            camera.setPreviewDisplay(mPreviewDisplay);
        } // try
        catch (final IOException e)
        {
            streamer.stop();
            camera.release();
            throw e;
        } // catch

        mMJpegHttpStreamer = streamer;
        camera.startPreview();
        mCamera = camera;
    } // synchronized
}
 
Example 20
Source File: SettingsFragment.java    From mlkit-material-android with Apache License 2.0 4 votes vote down vote up
private void setUpRearCameraPreviewSizePreference() {
  ListPreference previewSizePreference =
      (ListPreference) findPreference(getString(R.string.pref_key_rear_camera_preview_size));
  if (previewSizePreference == null) {
    return;
  }

  Camera camera = null;
  try {
    camera = Camera.open(CameraSource.CAMERA_FACING_BACK);
    List<CameraSizePair> previewSizeList = Utils.generateValidPreviewSizeList(camera);
    String[] previewSizeStringValues = new String[previewSizeList.size()];
    Map<String, String> previewToPictureSizeStringMap = new HashMap<>();
    for (int i = 0; i < previewSizeList.size(); i++) {
      CameraSizePair sizePair = previewSizeList.get(i);
      previewSizeStringValues[i] = sizePair.preview.toString();
      if (sizePair.picture != null) {
        previewToPictureSizeStringMap.put(
            sizePair.preview.toString(), sizePair.picture.toString());
      }
    }
    previewSizePreference.setEntries(previewSizeStringValues);
    previewSizePreference.setEntryValues(previewSizeStringValues);
    previewSizePreference.setSummary(previewSizePreference.getEntry());
    previewSizePreference.setOnPreferenceChangeListener(
        (preference, newValue) -> {
          String newPreviewSizeStringValue = (String) newValue;
          previewSizePreference.setSummary(newPreviewSizeStringValue);
          PreferenceUtils.saveStringPreference(
              getActivity(),
              R.string.pref_key_rear_camera_picture_size,
              previewToPictureSizeStringMap.get(newPreviewSizeStringValue));
          return true;
        });

  } catch (Exception e) {
    // If there's no camera for the given camera id, hide the corresponding preference.
    if (previewSizePreference.getParent() != null) {
      previewSizePreference.getParent().removePreference(previewSizePreference);
    }
  } finally {
    if (camera != null) {
      camera.release();
    }
  }
}