How to turn on the Android Flashlight

后端 未结 5 992
南方客
南方客 2021-01-02 05:44

Update

Check out my answer

Original

I\'m trying to turn on the camera flashlight on the LG Revolution within my pro

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-02 06:18

    I thought I would update this with some bullet prof code that works on almost all 4.0+ devices.

    public void turnOn() {
        camera = Camera.open();
        try {
            Parameters parameters = camera.getParameters();
            parameters.setFlashMode(getFlashOnParameter());
            camera.setParameters(parameters);
    
            camera.setPreviewTexture(new SurfaceTexture(0));
    
            camera.startPreview();
            camera.autoFocus(this);
        } catch (Exception e) {
            // We are expecting this to happen on devices that don't support autofocus.
        }
    }
    
    private String getFlashOnParameter() {
        List flashModes = camera.getParameters().getSupportedFlashModes();
    
        if (flashModes.contains(FLASH_MODE_TORCH)) {
            return FLASH_MODE_TORCH;
        } else if (flashModes.contains(FLASH_MODE_ON)) {
            return FLASH_MODE_ON;
        } else if (flashModes.contains(FLASH_MODE_AUTO)) {
            return FLASH_MODE_AUTO;
        }
        throw new RuntimeException();
    }
    

    The real key is setting that fake SurfaceTexture so that the preview will actually start. Turning it off is very easy as well

    public void turnOff() {
            try {
                camera.stopPreview();
                camera.release();
                camera = null;
            } catch (Exception e) {
                // This will happen if the camera fails to turn on.
            }
    }
    

提交回复
热议问题