Cant open Camera Servoce Android - 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

Related

Camera flash not turning off

So I'm working on an Activity where you're supposed to take a picture and then uploading it to a Parse server.
Everything is working fine except for the flash mode; turning it on works but turning it off doesn't work.
This is my code for turning the flash on:
private void turnOnFlash() {
Camera.Parameters params = camera.getParameters();
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
params.setFlashMode(Camera.Parameters.FLASH_MODE_ON);
camera.setParameters(params);
isFlashOn = true;
// Show the flash mode in a Toast.
Toast.makeText(this, "Flash mode: " + camera.getParameters().getFlashMode(), Toast.LENGTH_SHORT).show();
// Changing button image.
imgFlash.setImageResource(R.drawable.ic_flash_on_white_48dp);
}
}
This is my code for turning the flash off:
private void turnOffFlash() {
Camera.Parameters params = camera.getParameters();
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
isFlashOn = false;
// Show the flash mode in a Toast.
Toast.makeText(this, "Flash mode: " + camera.getParameters().getFlashMode(), Toast.LENGTH_SHORT).show();
// Changing button image.
imgFlash.setImageResource(R.drawable.ic_flash_off_white_48dp);
}
}
Any help would be appreciated.
EDIT
The Toast that shows the flash mode shows Flash mode: off when the turnOffFlash() method is called, but the flash remains on.

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.

How to alter the deprecated Camera class in Android

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) {
}
}

Torch/Flashlight won't turn on with Android app

I am practicing building Android apps and figured starting with a flashlight would be a great beginner step. After having my code blow up several times, I have the app stable where it no longer force closes.
However, the LED camera flash doesn't turn on like I was hoping it should.
Any insight as to what I'm doing wrong would be most helpful.
public class PMATorch extends Activity {
private Camera camera;
private Button button;
private Camera.Parameters param;
private boolean torchStat = false;
public Camera getCameraInstance() {
Camera c = null;
try {
c = camera.open();
} catch (Exception e) {
}
return c;
}
private void torchOn(){
if (camera != null){
Parameters param = camera.getParameters();
param.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(param);
camera.startPreview();
torchStat = true;
}
}
private void torchOff(){
if (camera != null){
Parameters param = camera.getParameters();
param.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(param);
camera.stopPreview();
torchStat = false;
}
}
#Override
protected void onDestroy() {
if (camera != null) {
camera.release();
camera = null;
}
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pmatorch);
camera = getCameraInstance();
button = (Button) findViewById(R.id.torchOnOff);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (torchStat = false) {
torchOn();
} else {
torchOff();
}
}
});
}
}
Edit: I have the permissions and features set in AndroidManifest.xml.
Edit 2: Updated the code to what I just tried running.
private Camera camera;
is never assigned anything. So if (camera != null){ in torchOn won't do anything. You probably wanted to do something like:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
camera = getCameraInstance(); // <<
public Camera getCameraInstance() {
Camera c = null;
try {
c = camera.open();
} catch (Exception e) {
}
return c;
}
has furthermore 2 minor problems:
* catch (Exception e) {} hides anything that might go wrong here. I would add at least a logging statement like Log.e("PMATorch", "getCameraInstance", e).
* Cosmetical issue: camera.open() screams NullPointerException at first glance. Change to Camera.open() - the method is static and belongs to the class.
E.g. (IMO nicer to read if you get rid of the local variable so I removed that as well)
public Camera getCameraInstance() {
try {
return Camera.open();
} catch (Exception e) {
Log.e("PMATorch", "getCameraInstance", e);
return null;
}
}
To further help with debugging such a problem. Add Log to the place that actually causes the action that doesn't seem to work.
private void torchOn(){
if (camera != null){
Log.d("PMATorch", "now actually turning on");
...
You will find that In many cases code you think is not working is actually not executed. When that happen, trace back the path that leads there, either with more log or by using the debugger and stepping though the code.
Instead of using Parameters.FLASH_MODE_ON, try using Parameters.FLASH_MODE_TORCH on your torchOn() method.
According to the documentation on Camera Parameters
Parameters.FLASH_MODE_ON: Flash will always be fired during snapshot.
Parameters.FLASH_MODE_TORCH: Constant emission of light during preview, auto-focus and snapshot.
In my understanding using Parameters.FLASH_MODE_ON will only turn on the light once and instantly or only if a picture is being taken. Parameters.FLASH_MODE_TORCH will constantly emit light so this option fits your requirement of having a light turned on when a button is pressed.
A nice tutorial on creating a flashlight application can be found here.

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