How to turn on the camera flash?

Asked

Viewed 5,650 times

3

I am not able to activate the camera flash to use as flashlight. The code I am running took from tutorials on the internet.

package com.getten.home;

import android.hardware.Camera;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

public class Login extends ActionBarActivity {

    private Toolbar pToolbar;

    private Camera mCamera;
    private boolean lFlashLigado = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        pToolbar = (Toolbar) findViewById(R.id.toolbar);
        pToolbar.setLogo(R.drawable.ic_launcher);
        setSupportActionBar(pToolbar);

        try {
            mCamera = Camera.open();
        } catch (Exception ex) {
            Log.e("Camera", "Impossível ouvir a câmera!");
        }
    }

    @Override
    protected void onPause() {
        if (mCamera != null) {
            mCamera.release();
            mCamera = null;
        }
        super.onPause();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.lanterna) {
            ligaDesligaFlash(lFlashLigado);
        }

        return true;
    }

    private void ligaDesligaFlash(boolean lDesliga) {
        if (lDesliga) {
            if (mCamera != null) {
                Camera.Parameters params = mCamera.getParameters();
                params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                mCamera.setParameters(params);
                mCamera.startPreview();

                lFlashLigado = false;
            }
        } else {
            if (mCamera != null) {
                Camera.Parameters params = mCamera.getParameters();
                params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                mCamera.setParameters(params);
                mCamera.startPreview();

                lFlashLigado = true;
            }
        }
    }
}

I am compiling the application in version "22". I have added everything that is permission, but I also had no success:

<uses-permission android:name="android.permission.WAKE_LOCK" />
<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" />

Someone would know how to solve, or some other way to do?

2 answers

1

First of all:

<uses-sdk android:minsdkversion="11" android:targetsdkversion="17">

Basically you need to:

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

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

The problem may be in your parole. Try using the event OnClickListener:

    ....
    //Detectando se o flash está ligado, inicialmente sim
    private boolean isLighOn = false;

    private Camera camera;

    private Button button;

    @Override
    protected void onStop() {
        super.onStop();

        if (camera != null) {
            camera.release();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        button = (Button) findViewById(R.id.botaoFlash);

        Context context = this;
        PackageManager pm = context.getPackageManager();

        // O mais importante: O aparelho possui configuração para câmera?
        if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            Log.e("err", "Aparelho não suporta camera!");
            return;
        }

        camera = Camera.open();
        final Parameters p = camera.getParameters();

        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                if (isLighOn) {

                    Log.i("informação", "Desligado!");

                    p.setFlashMode(Parameters.FLASH_MODE_OFF);
                    camera.setParameters(p);
                    camera.stopPreview();
                    isLighOn = false;

                } else {

                    Log.i("informação", "ligado!");

                    p.setFlashMode(Parameters.FLASH_MODE_TORCH);

                    camera.setParameters(p);
                    camera.startPreview();
                    isLighOn = true;

                }

            }
        });

    }
}
  • Thank you very much... I believe to be a problem with <uses-sdk android:minsdkversion="11" android:targetsdkversion="17"> .

  • Check here if it works.

  • I couldn’t make it work. The error message shown is: java.lang.Runtimeexception: Unable to start Activity Componentinfo{com.teste.flash/com.teste.flash.flash}: java.lang.Runtimeexception: Fail to connect to camera service

1


First you must change your AndroidManifest.xml and add permissions:

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

After that in one button onClick event make the following code:

private Camera mCamera;

public void ligarLed(View v) {
    mCamera = Camera.open();
    if( mCamera != null ){
            Parameters params = mCamera.getParameters();
            params.setFlashMode( Parameters.FLASH_MODE_TORCH );
            mCamera.setParameters( params );
     }
}

What Switches On or Off Flash is the enumerator

Parameters.FLASH_MODE_TORCH
Parameters.FLASH_MODE_OFF 

Don’t forget that after using Flash you must release the camera with the following code:

mCamera.release();
mCamera = null;
  • The above mentioned error occurs at the time I execute the camera = Camera.open(); @Eduardo Binotto, I developed exactly as you directed me, and the same error persists. It might be some configuration of the phone, is an Xperia (Android 5.0.2)?

  • Good evening @Maicon, you can put one try catch and send the error that is happening so that we can analyze and find a solution to this problem.

  • First thanks for the personal help... The error message that displays is: 'Fail to connect to camera service'. Code used: try{&#xA; camera = Camera.open();&#xA; }catch(Exception ex){&#xA; Log.e("err", ex.getMessage());&#xA; }

  • I’ve been going over your code, and you’re just releasing your camera on onPause. Change onPause code and put in your link methodDesligaFlash. The error is because the camera is not available.

  • Eduardo, I found the problem: I was inserting the permissions inside the tag application .... After I played the uses-permission outside it worked. In the console of Android Studio still appears some messages of connection failure, however, the flash is working. Thanks for the help! Thanks.

  • Glad you could make it, I’m very happy to be able to help you. If you can put my answers as the best answer to the question, I’m very grateful. Thank you.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.