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;
}
}
Related
I am facing a problem in a custom camera application. With the flash function turned ON, the phone takes the 1st photo with flash, but on the 2nd photo it doesn't use the flash.
flashCameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isPressed) {
flashCameraButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.onflash));
flashOnButton();
} else if (isPressed) {
flashCameraButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.offflash));
isPressed = !isPressed;
flashOffButton();
} else
flashCameraButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.onflash));
flashOnButton();
}
});
private void flashOnButton() {
if (camera != null) {
try {
Camera.Parameters param = camera.getParameters();
param.setFlashMode(!flashmode ? Camera.Parameters.FLASH_MODE_ON
: Camera.Parameters.FLASH_MODE_ON);
camera.setParameters(param);
flashmode = !flashmode;
} catch (Exception e) {
// TODO: handle exception
}
}
}
private void flashOffButton() {
if (camera != null) {
try {
Camera.Parameters param = camera.getParameters();
param.setFlashMode(!flashmode ? Camera.Parameters.FLASH_MODE_OFF
: Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(param);
flashmode = !flashmode;
} catch (Exception e) {
// TODO: handle exception
}
}
}
Take a look at the code below. You can do something similar to it:
btnSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
// turn off flash
//change the picture
turnOffFlash();
} else {
// turn on flash
//change the picture
turnOnFlash();
}
}
});
}
// Get the camera
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
// Turning On flash
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
}
}
// Turning Off flash
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
}
}
What we are doing here is checking if the Flash is ON or OFF, if it is ON, we call the method turnOffFlash() to turn it off and if it is OFF we call the method turnOnFlash() to turn it on.
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.
In a previous way, flashlight feature could be used by using Camera class. But now that the entire Camera and Camera-related classes in android.hardware packages are deprecated, I should alternatively use some other classes in the android.hardware.camera2 package.
Traditionally, I coded the flashlight part like this.
// getting camera parameters
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
/*
* Turning On flash
*/
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}
}
But now with the new API I'm getting so confused how to use the new one. Can anybody explain?
for flashlight I advise using the Camera2 API only from Android 6 (api 23), my function for toggling the flashlight looks like
#TargetApi(Build.VERSION_CODES.M)
public void toggleMarshmallowFlashlight(boolean enable) {
try {
final CameraManager manager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
final String[] list = manager.getCameraIdList();
manager.setTorchMode(list[0], enable);
} catch (CameraAccessException e) {
}
}
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
I'm working on a flashlight app using the camera flash. It seems to work fine but on occasion calling camera.release() causes a hang for about a minute or so. I've included the code below. I've looked at a bunch of examples and I don't see anything that could cause such a thing. Any ideas?
//latest
public void setOn(boolean on, Context context) {
if (lock) {
Log.i(TAG, "lock: true");
return;
}
if (on) {
if (mCamera == null) {
mCamera = Camera.open();
}
Parameters params = mCamera.getParameters();
params.setFlashMode(MODE_TORCH);
mCamera.setParameters(params);
mCamera.startPreview();
} else {
if (mCamera != null) {
try {
Parameters params = mCamera.getParameters();
params.setFlashMode(MODE_OFF);
mCamera.setParameters(params);
} finally {
new Thread(new Runnable() {
public void run() {
Log.i(TAG, "new Thread - start");
lock = true;
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
mCamera.release();
mCamera = null;
lock = false;
Log.i(TAG, "new Thread - end");
}
}).start();
}
}
}
}
//original
public void setOn(boolean on, Context context) {
Camera camera = mCamera;
if (on) {
if (camera == null) {
mCamera = camera = Camera.open();
}
Parameters params = camera.getParameters();
params.setFlashMode(MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
} else {
if (camera != null) {
try {
Parameters params = camera.getParameters();
params.setFlashMode(MODE_OFF);
camera.setParameters(params);
} finally {
camera.stopPreview();
camera.release();
mCamera = camera = null;
}
}
}
}
Try putting it in a thread to run in the background so it wont hang up the UI.
new Thread(new Runnable(){
public void run(){
camera.setPreviewCallback(null); // PreviewCallback de_init.
camera.stopPreview(); // stop Preview
camera.release();
}
}).start();
For me, the solution that works is:
Try{
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
} catch (Exception e){
//...
}
I`ve solved this isuue adding camera.unlock() before release()
camera.stopPreview();
camera.setPreviewCallback(null);
camera.unlock();
camera.release();
camera = null;
test on more devices needed...
just call your methods like
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.release();
you have to call setPreviewCallback(null) betweeen stopPreview and camera.releass