How to ON & OFF flash camera in services - android

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 !!!

Related

android camera application flash

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.

What should i do so that camera work everytime?

I am using camera service in my application. Sometimes the camera service is running fine in the application and sometimes it gives a runtime exception.
I have put Camera.Open() in try block and i have catched the exception and its showing in log cat
03-12 13:52:42.211: D/crazy(12686): in catch1
03-12 13:52:42.211: D/crazy(12686): java.lang.RuntimeException: Fail to connect to camera service
The code that i done is...
TelephonyManager mgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
int callState = mgr.getCallState();
//state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if(callState==TelephonyManager.CALL_STATE_RINGING) {
try {
cam = Camera.open();
p = cam.getParameters();
String myString = "0101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101011";
long blinkDelay = 50;
for (int i = 0; i < myString.length(); i++) {
//state=intent.getStringExtra(TelephonyManager.EXTRA_STATE);
callState = mgr.getCallState();
if (callState==TelephonyManager.CALL_STATE_IDLE){
p.setFlashMode(Parameters.FLASH_MODE_OFF);
cam.release();
break;
}else if (callState==TelephonyManager.CALL_STATE_OFFHOOK){
p.setFlashMode(Parameters.FLASH_MODE_OFF);
cam.release();
break;
}
if (myString.charAt(i) == '0') {
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
} else {
p.setFlashMode(Parameters.FLASH_MODE_OFF);
cam.setParameters(p);
}
Thread.sleep(blinkDelay);
}
}catch (Exception e) {
// TODO: handle exception
Log.d(tag, "in catch1");
Log.d(tag, e.toString());
}
It's probably because it is already used.
The javadoc for open states :
If the same camera is opened by other applications, this will throw a RuntimeException.
You must call release() when you are done using the camera, otherwise it will remain locked and be unavailable to other applications.
Your application should only have one Camera object active at a time for a particular hardware camera.
Make sure you always release the camera (even in case of exception, use finally) and check if there is no other application using it.
This comes from the android docs here. So long as you remember to release the camera when you're done (at at least before you try to get a new instance) you should be fine. I recommend reading the rest of that document as well. It is very helpful.
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;
}
}

Switch ON/OFF only Flash in 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();
}

app hanging on camera.release()

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

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