5

In one of the requirement in my app I need to pop up an activity containing the front camera preview,at this same time I need to turn on the flashlight as well.However I observe that,I am able to turn on the flashlight and back camera but not front camera and flashlight together.Following is my code:

    public class Cam extends Activity {

        private static int cameraId = 0;
        private Camera camera;

        //Adding for camera preview
        public static FrameLayout preview;
        public static CameraPreview mPreview;
        Context context;

        ImageButton btnSwitch;
        private boolean isFlashOn;
        private boolean hasFlash;
        Parameters params;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            Log.e("Cam","Inside onCreate");
            setContentView(R.layout.cam);
            context = getApplicationContext();      

            btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);

            hasFlash = getApplicationContext().getPackageManager()
                    .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

            startCamera();

            // displaying button image
            toggleButtonImage();        

            btnSwitch.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (isFlashOn) {
                        turnOffFlash();
                    } else {
                        turnOnFlash();
                    }
                }
            });     
        }

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

            turnOffFlash();

            Log.e("Cam","Inside onPause");
            try {
                if (camera != null) {
                    camera.release();
                    camera = null;
                    preview.removeView(mPreview);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

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

            Log.e("Cam","Inside onResume");
            try {
                if(camera ==null) {
                    Log.d("Cam","in resume,camera is  null");
                    try {
                        camera = android.hardware.Camera.open(cameraId); //opens front cam              
                        // camera = Camera.open(); when I use this I can on/off the flashlight,since I am using the back camera.
                        mPreview = new CameraPreview(this, camera);
                        preview = (FrameLayout) findViewById(R.id.camera_preview);
                        preview.addView(mPreview);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        protected void onDestroy() {
            super.onDestroy();
            Log.e("Cam","Inside onDestroy");
            if (camera != null) {
                try {
                    camera.release();
                    camera = null;
                    preview.removeView(mPreview);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        private void startCamera() {

                    Log.e("Cam","Inside doInBackground");
                    String msg = "";
                    // Do we have a camera?
                    try {
                        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {

                        } else {
                            cameraId = AppFunctions.findFrontFacingCamera();//A function that returns 0 for front camera
                            if (cameraId < 0) {

                            } else {

                                try {
                                    camera = Camera.open(cameraId);//opens front cam 
                                    // camera = Camera.open(); when I use this I can on/off the flashlight,since I am calling the back camera.
                                    params = camera.getParameters(); 
                                    Log.e("Cam","camera id" + cameraId);
                                    Log.e("Cam","params" + params);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                                try {
                                    mPreview = new CameraPreview(getApplicationContext(), camera);
                                    preview = (FrameLayout) findViewById(R.id.camera_preview);
                                    preview.addView(mPreview);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    } catch (Exception e3) {
                        e3.printStackTrace();
                    }
        }

        private void turnOnFlash() {
            Log.v("Cam","Inside turnOnFlash");
            if (!isFlashOn) {
                if (camera == null || params == null) {
                    Log.v("Cam","camera or param is null");
                    return;
                }

                params.setFlashMode(Parameters.FLASH_MODE_TORCH);
                camera.setParameters(params);
                camera.startPreview();
                isFlashOn = true;

                // changing button/switch image
                toggleButtonImage();
            }

        }

        /*
         * Turning Off flash
         */
        private void turnOffFlash() {
            Log.v("Cam","Inside turnOffFlash");
            if (isFlashOn) {
                if (camera == null || params == null) {
                    Log.v("Cam","camera or param is null");
                    return;
                }
                params.setFlashMode(Parameters.FLASH_MODE_OFF);
                camera.setParameters(params);
                camera.stopPreview();
                isFlashOn = false;

                // changing button/switch image
                toggleButtonImage();
            }
        }

        private void toggleButtonImage(){
            if(isFlashOn){
                btnSwitch.setImageResource(R.drawable.btn_switch_on);
            }else{
                btnSwitch.setImageResource(R.drawable.btn_switch_off);
            }
        }
    }

Manifest

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

How can I turn on the flashlight and front cam simultaneously? Any help would be appreciated !

Basher51
  • 1,319
  • 1
  • 17
  • 28
  • take a look at this answer: http://stackoverflow.com/a/25020259/1116216 – Michele La Ferla Nov 09 '14 at 10:43
  • @MicheleLaFerla: Here I believe they use 'camera = Camera.open();', which opens by default the back camera.I need to use the front cam instead.Moreover,I observe that a parameter created using the front cam object does not help me to on/off the flashlight – Basher51 Nov 09 '14 at 14:32
  • If I go by your requirement, What I understand is you just need to open the flashlight: "Ideally,any solution wherein if we can operate the flashlight without using any cameras object would be the best." Correct me if I am wrong. This seems like what you are looking for: http://stackoverflow.com/questions/6068803/how-to-turn-on-camera-flash-light-programmatically-in-android – Surendra Kumar Nov 14 '14 at 14:10
  • @SurendraKumar:Thanks for your suggestion.Firstly,I not only need to open the flashlight,but at the same time I want to be able to use the front camera simultaneously.Secondly, all the solutions Iv seen so far make use of the back camera object to operate the flashlight(I dont understand why android has tied/restricted using the flashlight with a camera object :/). – Basher51 Nov 15 '14 at 12:40
  • @SurendraKumar:Thirdly,did you notice that all the solutions in the link you suggested use camera.open() just prior to using the flashlight? This step by default opens the back camera.If I try to use the front cam object to use flashlight,then the flashlight doesnt turn on/off.It seems android has 'tied' the flashlight to operate only with the back cam objects parameter. – Basher51 Nov 15 '14 at 12:41
  • It should not be this way. I will check and update you. :) – Surendra Kumar Nov 17 '14 at 14:15

3 Answers3

1

Flashlight

 public void onToggleClicked(View view) {
    PackageManager pm = context.getPackageManager();
    final Parameters p = camera.getParameters();
    if (isFlashSupported(pm)) {
        boolean on = ((ToggleButton) view).isChecked();
        if (on) {
            Log.i("info", "torch is turn on!");
            p.setFlashMode(Parameters.FLASH_MODE_TORCH);
            camera.setParameters(p);
            camera.startPreview();
        } else {
            Log.i("info", "torch is turn off!");
            p.setFlashMode(Parameters.FLASH_MODE_OFF);
            camera.setParameters(p);
            camera.stopPreview();
        }

Camera :

 ImageButton ib = (ImageButton) findViewById(R.id.buttonToast);
    ib.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(i, CAPTURE_IMAGE_CAPTURE_CODE);
        }
    });
Michele La Ferla
  • 6,775
  • 11
  • 53
  • 79
Machan Max
  • 89
  • 1
  • 10
  • For line of code 'final Parameters p = camera.getParameters();' ,are you using camera = Camera.open()? . If so,that opens the back camera and this parameter 'p' doesnt help in turning on/off the flashlight since its coming from the object of back cam.Please correct me if I'm wrong. – Basher51 Nov 09 '14 at 12:22
1

Try to turn on the flashlight in background then open your front camera. actually you can turn front camera and flashlight in background.

Here how to open flashlight in background: this

Here how to turn on camera in background: this

Community
  • 1
  • 1
  • In both the links that you have shared I see that the camera object is created using 'camera = Camera.open();'.This I believe opens the back cam by default.A parameter create using this back cameras object did not help me in turning on/off the flashlight.I tried the same,as shown in my question.Pls correct me if I'm wrong. – Basher51 Nov 09 '14 at 12:41
0

The following code checks for the availability of a front camera:

private Camera openFrontFacingCameraGingerbread() {
    int cameraCount = 0;
    Camera cam = null;
    Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
    cameraCount = Camera.getNumberOfCameras();
    for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
        Camera.getCameraInfo(camIdx, cameraInfo);
        if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            try {
                cam = Camera.open(camIdx);
            } catch (RuntimeException e) {
                Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
            }
        }
    }

    return cam;
}

Then add the following permissions in the AndroidManifest.xml file:

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

Note: This feature is available in Gingerbread(2.3) and Up Android Version.

I recommend using surfaceView like in this example to implement a working flashlight.

Hope this helps :)

Michele La Ferla
  • 6,775
  • 11
  • 53
  • 79
  • The line in my code - 'cameraId = AppFunctions.findFrontFacingCamera();' does the function to fetch the id of the front camera,and its working fine .The problem I am facing is that when I create a parameter,'params = camera.getParameters();' this uses the front camera object.When this param is used to turn on/off flashlight it doesnt work.Had this param been from the back camera object then the flashlight is working. – Basher51 Nov 09 '14 at 14:46
  • it is supposed to open the front camera as you are looping on the number of cameras available. – Michele La Ferla Nov 09 '14 at 14:48
  • Yes agreed.All that is working fine and I am able to open the front camera.But at this stage when I am creating the parameter using the front camera object(params = camera.getParameters();) and then when using it for flashlight (params.setFlashMode(Parameters.FLASH_MODE_TORCH);) , I observe that I am not able to operate the flashlight. – Basher51 Nov 09 '14 at 14:50
  • Understood. THen you need to create 2 different instances of camera, for the device to load the front lens and the back flashlight. Personally, I never programmed it, but I can see what you are trying to do. – Michele La Ferla Nov 09 '14 at 14:54
  • I don't think the system allows to open both cams at the same time.I have uploaded my sample app source code at - 'https://drive.google.com/file/d/0B_gufkZm3wBEbzF5Vms3S21pVzQ/view?usp=sharing' .You may run the app/view source code if you wish to see my issue. – Basher51 Nov 09 '14 at 14:56
  • I have tried to make a quick search for you. The following seems to work, at least on HTC phones with a front and back camera: https://bitbucket.org/jens_grubert/androiddualcameracapture/ – Michele La Ferla Nov 09 '14 at 15:07