Switch ON/OFF only Flash in Android - android

I am trying to use the phone's camera flash to be used a torch. I have a button that toggles between ON and OFF but for some reason the below code is not working. I know there are couple of questions already on this but none of them are giving correct answers.
Can somebody help me out?
Code to ON/OFF flash:
camera = Camera.open();
final Parameters p = camera.getParameters();
flashon.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
if (isFlashOn)
{
Log.e("Flash", "Flash is turned off!");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
isFlashOn = false;
flashon.setText("Flash ON");
}
else
{
Log.i("Flash", "Flash is turned on!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
isFlashOn = true;
flashon.setText("Flash OFF");
}
}
});
The following are the manifest details:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
Awaiting your response!
Thanks!

What happens when you do it this way?
Maybe you have a problem because you are setting p as final.
camera = Camera.open();
flashon.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
if (isFlashOn)
{
Log.e("Flash", "Flash is turned off!");
camera.setParameters(camera.getParameters().setFlashMode(Parameters.FLASH_MODE_OFF));
isFlashOn = false;
flashon.setText("Flash ON");
}
else
{
Log.i("Flash", "Flash is turned on!");
camera.setParameters(camera.getParameters().setFlashMode(Parameters.FLASH_MODE_TORCH));
isFlashOn = true;
flashon.setText("Flash OFF");
}
}
});

Try this piece of code. This works for me.
private Camera camera;
private Parameters p;
//initialize camera instance
private void initCamera() {
try{
camera = Camera.open();
p=camera.getParameters();
}catch (Exception e){
camera = null;
}
}
//start flashing
private void startFlashing() {
initCamera();
if(camera!=null && this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)){
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
}

Related

Android flashlight code not working

I created a simple project to play with flashlight feature. From many different places (which all do it basically the same way), I have assembled the following code, but the flashlight will not turn on (No exceptions are raised) - but it works with the camera when I take a photo:
Example code
Example code 2
Example Code 3
#Override
protected void onResume() {
super.onResume();
try {
// check flashlight support
hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
return;
}
text_off = (TextView) findViewById(R.id.text_off);
text_off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
return;
}
});
getCamera();
turnOnFlash();
} catch (Exception e) {
Log.e(this.getClass().getSimpleName(), "onResume Error: "+e.getMessage());
}
}
#Override
protected void onPause() {
super.onPause();
turnOffFlash();
}
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e(this.getClass().getSimpleName(), "Camera Error. Failed to Open. Error: "+e.getMessage());
}
}
}
#SuppressWarnings("deprecation")
private void turnOnFlash() {
try {
Log.d(this.getClass().getSimpleName(), "turnOnFlash CHECKPOINT ");
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
// ALSO TRIED: params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
Log.d(this.getClass().getSimpleName(), "turnOnFlash CHECKPOINT EXIT");
} catch (Exception e) {
Log.e(this.getClass().getSimpleName(), "Camera Error. Failed to Open. Error: "+e.getMessage());
}
}
#SuppressWarnings("deprecation")
private void turnOffFlash() {
try {
Log.d(this.getClass().getSimpleName(), "turnOffFlash CHECKPOINT ");
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
camera.release();
isFlashOn = false;
} catch (Exception e) {
Log.e(this.getClass().getSimpleName(), "Camera Error. Failed to Open. Error: "+e.getMessage());
}
}
In manifest:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
Why doesn't this code turn the flashlight on/off?
Hardware: Nexus 5
OS: Android Marshmallow
I think you are missing one additional line of code, which is needed for some devices. These 3 lines are whats needed on all devices I encountered so far:
// will work on some devices
mCamera.setParameters(parameters);
// Needed for some devices.
mCamera.setPreviewTexture(new SurfaceTexture(0));
// Needed for some more devices.
mCamera.startPreview();
If you add some dummy SurfaceTexture it should work. Also you can see a full code sample here.
The camera api varies highly between phones and those phone details are poorly documented.

Cant open Camera Servoce Android

i stuck here with a Problem. Trying to build a torch app. Works fine, but when i switch fragment or go to homescreen and come back the flash light wont work. Error is failed to connect to camera service.
I think the Problem is, that I create a new Camera instance then, and the new cant connect to the camera anymore. But how should i solve it?
public class FlashCameraManager {
private boolean isFlashOn;
private Camera camera;
public Camera.Parameters params;
// getting camera parameters
public void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
camera = null;
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
} else {
camera.release();
camera = null;
}
}
public void FlashOnOff()
{
//Flash Aktivieren oder deaktivieren
if (isFlashOn)
{
//Turn Flash off
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
Log.d("FlashCameraManager", "Turning Flash off");
}
else
{
// Turn Flash on
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
Log.d("FlashCameraManager", "Turning Flash on");
}
}
public boolean isFlashActive()
{
//Prüfen ob Flash an oder aus ist
return isFlashOn;
}}
This is from the MainActivity
final ImageButton flash = (ImageButton) rootView.findViewById(R.id.none_flash);
if(camera == null) {
camera = new FlashCameraManager();
}
camera.getCamera();
flash.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Content
if (camera.isFlashActive())
{
//Turn Flash off
camera.FlashOnOff();
Log.d("NoneFragment", "Turning Flash off");
flash.setActivated(false);
}
else
{
//Turn Flash on
camera.FlashOnOff();
Log.d("NoneFragment", "Turning Flash on");
flash.setActivated(true);
}
}} );
After you are done with the camera (i.e. before exiting the application or launching another activity) make sure that you release the camera resources by calling the method release(), which, per the API Guide, "Disconnects and releases the Camera object resources". The API guide also provides some valueable insight into properly utilizing the class and performing simple operations, such as tasking a picture. The API Guide may be found here:
http://developer.android.com/reference/android/hardware/Camera.html
You might also want to consider taking a glance at the new camera API (android.hardware.camera2), as the current API that you are using is deprecated as of API level 21. The guide for the new API is found here:
http://developer.android.com/reference/android/hardware/camera2/package-summary.html

How to ON & OFF flash camera in services

well i'm using service to On & OFF flash light of camera,it's working fine but my mobile camera app is crashing, i'm not able to release camera in service
Camera camera = Camera.open();
final Parameters p = camera.getParameters();
if (isFlashOn)
{
Log.i("info", "torch is turned off!");
Toast toast= Toast.makeText(getApplicationContext(),
"Torch is turned off!",Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 100);
toast.show();
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
//Set flag to false
isFlashOn = false;
release=true;
}
//If Flag is set to false
else
{
Log.i("info", "torch is turned on!");
Toast toast= Toast.makeText(getApplicationContext(),
"Torch is turned on!",Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 100);
toast.show();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
isFlashOn = true;
release=false;
}
if (release == true)
{
camera.stopPreview();
camera.release();
}
You have to open Camera safely so for that you have to check camera state before the directly open your camera.
private boolean safeCameraOpen(int id) {
boolean qOpened = false;
try {
releaseCameraAndPreview();
mCamera = Camera.open(id);
qOpened = (mCamera != null);
} catch (Exception e) {
Log.e(getString(R.string.app_name), "failed to open Camera");
e.printStackTrace();
}
return qOpened;
}
private void releaseCameraAndPreview() {
mPreview.setCamera(null);
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
For Further Details about Camera check it out and adjust as per your needs.
Enjoy !!!

Android Camera LED light goes to Off after 2 seconds?

I am using the camera flash light in my application, I was done coding for that, it's working on/off the light.
but after 2 seconds it goes to off. If I press the on button again it was giving force close.
This is the code i am using for this, please help me.
I want this like if user presses the on button light On, upto user press Off button.
private void processOffClick() {
//togglebutton.setButtonDrawable(R.drawable.offbutton);
System.out.println("in off state");
if( cam != null ){
cam.stopPreview();
cam.release();
}
}
private void processOnClick() {
//togglebutton.setButtonDrawable(R.drawable.onbutton);
System.out.println("in on state");
cam = Camera.open();
Parameters params = cam.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
cam.setParameters(params);
cam.startPreview();
cam.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});
}
put the lines:
Parameters params = cam.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
cam.setParameters(params);
in processOffClick instead of putting it in processOnClick
like that:
boolean clicked = false;
private void processOffClick() {
//togglebutton.setButtonDrawable(R.drawable.offbutton);
clicked = false;
System.out.println("in off state");
if( cam != null ){
cam.stopPreview();
cam.release();
}
}
private void processOnClick() {
clicked = true;
//togglebutton.setButtonDrawable(R.drawable.onbutton);
System.out.println("in on state");
cam = Camera.open();
Parameters params = cam.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
while(clicked) {
cam.setParameters(params);
cam.startPreview();
cam.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});
}
}
It might work, i didn't check the code
I added a while loop so it would hold the flash and the focus until its unclicked.
My experience says, that flash mode ought to be "TORCH" ( if supported ) and it is started only when you start preview. However, cameras behave very differently on different devices and not always as advertised in their capabilities descrioptors
1.Turn on
camera = Camera.open();
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
2. Turn off
camera = Camera.open();
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
And, put following permission on AndroidManifest.xml.
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
see this one http://www.mkyong.com/android/how-to-turn-onoff-camera-ledflashlight-in-android/

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.
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.
}
}
It seems like the developer of the Tiny Flashlight + LED app on the Android Market figured out how to make the flashlight work on LG Revolution.
Maybe you can contact him and ask?
You can also check the permissions he is using in his app to try to make your app work!
Good luck!
Test this :
if(camera == null){
camera = Camera.open();
parameters = camera.getParameters();
List<String> flashModes = parameters.getSupportedFlashModes();
if(flashModes != null && flashModes.contains(Parameters.FLASH_MODE_TORCH)){
//appareil supportant le mode torch
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
} else if (flashModes != null && flashModes.contains(Parameters.FLASH_MODE_ON)){
//spécial samsung
parameters.setFlashMode(Parameters.FLASH_MODE_ON);
camera.setParameters(parameters);
camera.startPreview();
camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) { }
});
} else {
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
}
parameters.setFlashMode( Parameters.FLASH_MODE_OFF );
camera.setParameters(parameters);
camera.release();
camera = null;
} catch (RuntimeException e) {}
}//if
This worked well for LG Nexus:
camera = Camera.open();
camera.setPreviewTexture(new SurfaceTexture(0));
camera.setParameters(p);
camera.startPreview();
/*TESTED LG G4 */
public void flashOnOff(){
List<String> flashModes = parameter001.getSupportedFlashModes();
if(flashModes != null && flashModes.contains(Parameters.FLASH_MODE_TORCH)){
//appareil supportant le mode torch
parameter001.setFlashMode(Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(parameter001);
} else if (flashModes != null && flashModes.contains(Parameters.FLASH_MODE_ON)){
//spécial samsung
parameter001.setFlashMode(Parameters.FLASH_MODE_ON);
mCamera.setParameters(parameter001);
mCamera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) { }
});
} else {
parameter001.setFlashMode(Parameters.FLASH_MODE_OFF);
mCamera.setParameters(parameter001);
}
if (!isFlashOn) {
if (mCamera == null || parameter001 == null) {
return;
}
parameter001 = mCamera.getParameters();
parameter001.setFlashMode(Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(parameter001);
try {
mCamera.setPreviewTexture(new SurfaceTexture(0));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mCamera.startPreview();
isFlashOn = true;
// changing button/switch image
}else if (isFlashOn) {
if (mCamera == null || parameter001 == null) {
return;
}
parameter001 = mCamera.getParameters();
parameter001.setFlashMode(Parameters.FLASH_MODE_OFF);
mCamera.setParameters(parameter001);
mCamera.stopPreview();
isFlashOn = false;
}
}

Categories

Resources