Turn on the Flash led by pressing an item in Action bar

4

I'm trying to turn on the flash of the cell phone as a flashlight, from an item in the action bar, but I can not turn it on, the code is e as follows:

Variable delcara at the start of the calse to manage the on and off:

    boolean isOn = false;

Menu options:

    public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();
    if (id == R.id.btnOtro) {

    }
    if(id== R.id.btnFlash) {

        if(isOn==false)
            isOn=true;
        else{
            isOn=false;
        }
        flash();
        }
    return super.onOptionsItemSelected(item);
}

And this is the method to start the flash:

     public void flash()//  metodo para activar el flash
    {
    if(getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {

        camera= Camera.open();
        parameters = camera.getParameters();
    }

    if(isOn==true)
    {
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
        camera.setParameters(parameters);
        camera.startPreview();
    }
    else
    {
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
        camera.setParameters(parameters);
        camera.stopPreview();
    }
}

If someone solved something like that, it would be very useful for me to share, Thank you.

    
asked by Gerardo Figueroa 02.06.2016 в 20:28
source

1 answer

2

Do you have the permissions added in AndroidManifest.xml ?

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

Regarding your validation that determines if your device has a flash, you must change it, since it is probably returning a false value, for that reason it does not open the camera.

if(getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
...

a:

if(hasFlash()) {
...

using this method:

public boolean hasFlash() {
        if (camera == null) {
            return false;
        }
        Camera.Parameters parameters = camera.getParameters();

        if (parameters.getFlashMode() == null) {
            return false;
        }    
        List<String> supportedFlashModes = parameters.getSupportedFlashModes();
        if (supportedFlashModes == null || supportedFlashModes.isEmpty() || supportedFlashModes.size() == 1 && supportedFlashModes.get(0).equals(Camera.Parameters.FLASH_MODE_OFF)) {
            return false;
        }   
        return true;
    }
    
answered by 03.06.2016 в 17:05