How to turn ON and OFF Device flash light?

RajaReddy PolamReddy picture RajaReddy PolamReddy · Oct 19, 2012 · Viewed 14.9k times · Source

I want to turn on only camera flash light (not with camera preview) programmatically in Android. I googled for it but the help I found was not working on my Samsung Galaxy ACE.

By using this code able to turn on for few seconds after that it goes to off automatically with out doing anything on the UI. If I try to turn on again getting force close.

private void turnOn() {

    clicked = true;      
    mCamera = Camera.open();
    Parameters params = mCamera.getParameters();
    params.setFlashMode(Parameters.FLASH_MODE_ON); 
    mCamera.setParameters(params);
    mCamera.startPreview();
    mCamera.autoFocus(new AutoFocusCallback() {
        public void onAutoFocus(boolean success, Camera camera) {
        }
    });
}

For turn OFF

private void turnOff() { 
    clicked = false;         
    if (mCamera != null) {
        mCamera.stopPreview();
        mCamera.release();
    }
}

Declared these manifest permissions

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

<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature android:name="android.hardware.camera.flash" />

Can any body tell me How to turn on the flash light for a long time upto the use click on OFF button. Is it requires any third party libraries. I saw this app in the Google play Tiny flash how they did this app..

From my after turn on it goes to off in 2 sec I did not get what's the problem in this.

Answer

user1475122 picture user1475122 · Oct 19, 2012

Try this

//Turn on
camera = Camera.open();
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();

//Turn off
camera = Camera.open();
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();