Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn on the Android Flashlight

Update

Check out my answer

Original

I'm trying to turn on the camera flashlight on the LG Revolution within my program. I use the torch mode method which works on most phones but not on LG phone. Does anyone know how to get it to work on LG's or specifically the Revolution?

Here's my manifest:

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.FLASHLIGHT"/>

Here's my current code:

public Camera camera = Camera.open();
    public Camera.Parameters Flash = camera.getParameters();

With my on create:

            Flash.setFlashMode("torch");
            Parameters p = camera.getParameters();
            camera.setParameters(Flash);
            camera.startPreview();

I've seen people use an auto focus but i don't know if that would work.

like image 234
MinceMan Avatar asked Aug 10 '11 01:08

MinceMan


People also ask

How do I activate my flashlight?

Tap the Quick Settings tile for the flashlightSwipe down on your status bar, then tap the Pencil icon. Scroll down and look for the Flashlight tile.

Is there a flashlight on an android?

To use the flashlight, open the Quick settings panel by swiping down from the top of the screen using two fingers. Next, tap the Flashlight icon to turn the light on or off. Depending on your setup, you may need to swipe left to see the Flashlight icon.


1 Answers

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<String> 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.
        }
}
like image 84
MinceMan Avatar answered Oct 10 '22 15:10

MinceMan