Turn on Flashlight on Motorola XYBoard - android

I am writing an app to turn on the flashlight for a fixed duration on my Motorola XYBoard . Below is my piece of code , While this code works on Motorola Attrix and Samsung Galaxy Note 10.1 its not working on the XYBoard. I did check the supported flash modes and torch is one of them . I have read multiple discussions on stack overflow where others faced a similar problem but nothing that I tried worked. Would be really helpful if someone to help me out
public void flashLightOn() {
try {
if (getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH)) {
cam = Camera.open();
Parameters p = cam.getParameters();
List<String> abc = p.getSupportedFlashModes();
for (String a : abc){
Log.d("mode: ", a);
}
p.setFlashMode(Parameters.FLASH_MODE_OFF);
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
/* cam.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});*/
} else {
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Exception flashLightOn()",
Toast.LENGTH_SHORT).show();
}
}
public void flashLightOff() {
try {
if (getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH)) {
cam.stopPreview();
cam.release();
cam = null;
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Exception flashLightOff",
Toast.LENGTH_SHORT).show();
}
}

Why don't you install one of the torchlight app from the App store and your app will just invoke the app using an intent.
This way less coding!

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.

Method Camera.takePicture() crash on Nexus 5, but Xperia mini is OK

At first please excuse my bad English.
I have problem with programmatically taking photo. I wrote an app, that makes collection of photos based on countdown timer and after that, photos are being processed using c++ code.
I'm using dummy SurfaceView, because I don't need preview in UI. The code below is working on my phone Xperia mini - API 15 (so permissions and code would be correct), but I borrowed school Nexus 5 - API 21 and there is problem with preview.
takePicture: camera 0: Cannot take picture without preview enabled
I found a solution, which uses setPreviewTexture (commented below) instead of setPreviewDisplay. It working for the first photo, which is normally saved, but I get the same error after the second call of takePicture().
Thanks for every advice, LS
Camera camera;
#Override
protected void onResume() {
super.onResume();
// is camera on device?
if(!checkCameraHardware()) return;
releaseCamera();
try {
camera.stopPreview();
} catch (Exception e){
Log.d(TAG, "No preview before.");
}
SurfaceView dummy = new SurfaceView(this);
camera = Camera.open();
Camera.Parameters params = camera.getParameters();
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
camera.setParameters(params);
try {
//camera.setPreviewTexture(new SurfaceTexture(10));
camera.setPreviewDisplay(dummy.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
camera.startPreview();
}
SOLUTION:
I needed to refresh preview. The code below is working on Xperie and Nexus too.
Question remains why I have to use setPreviewTexture, because setPreviewDisplay always returns error on Nexus.
camera.takePicture(null, null, new PictureCallback() {
#Override
public void onPictureTaken(final byte[] data, Camera camera) {
// save picture
refreshPreview();
}
});
public void refreshPreview() {
try {
camera.stopPreview();
} catch (Exception e) {}
try {
camera.startPreview();
} catch (Exception e) {}
}
and in function onResume()
try {
camera.setPreviewTexture(new SurfaceTexture(10));
} catch (IOException e) {}
Just add a callback for starting preview on your camera instance. The thing is that after starting preview on camera instance, it needs some time to be able take a picture. Try this:
camera.startPreview();
camera.setOneShotPreviewCallback(new Camera.PreviewCallback() {
#Override
public void onPreviewFrame(byte[] data, Camera camera) {
camera.takePicture(null, null, new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// do something you want with your picture and stop preview
camera.stopPreview();
}
});
Once the picture is taken, refresh you're surfaceview & stop the preview and releasee camera and restart the process again.
try {
camera.takePicture(null, null, new PictureCallback() {
public void onPictureTaken(final byte[] data, Camera camera) {
//once ur logic done
refreshCamera();
}
});
} catch (Exception e2) {
// Toast.makeText(getApplicationContext(), "Picture not taken", Toast.LENGTH_SHORT).show();
e2.printStackTrace();
}
public void refreshCamera() {
if (dummy.getHolder().getSurface() == null) {
return;
}
try {
camera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
try {
camera.setPreviewDisplay(dummy.getHolder());
camera.startPreview();
} catch (Exception e) {
}
}
Hope this solution may help you.

Android custom camera freeze after zoom

I have a custom camera that works fine in some devices. It works well on Samsung Galaxy Gran Duos (samsung-gt i9082, Android 4.2.2) but when I try to capture an image, that I zoomed in before, it freezes, no crash, the only way to get out is to press the back button. This happen only in the Samsung Galaxy Gran Duos.
The code that I used to take a picture:
Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
try {
} catch (Exception e) {
if (flePicture== null){
Log.d("camera", "Error creating media file, check storage permissions: " +
e.getMessage());
return;
}
}
try {
FileOutputStream fos = new FileOutputStream(flePicture);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d("camera", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("camera", "Error accessing file: " + e.getMessage());
}
}
};
And the code used for the zoom in:
private void zoomIn() {
if (pblnInPreview) {
Camera.Parameters parameters = camCamera.getParameters();
if ((parameters.getZoom() + 1) < parameters.getMaxZoom()) {
parameters.setZoom(parameters.getZoom() + 1);
camCamera.setParameters(parameters);
}
}
}
LogCat:
04-07 17:21:14.386: E/BrcmCamera(130): processControlBuffer: Corrupt stream error raised by camera - sensor communication failure
I think you need to confirm that your camera supports zoom by using camera.isZoomSupported() then if it is supported you need to cancel auto focus with camera.cancelAutoFocus() to prevent image distorsions.
But this will only work if your device actually supports zoom. If not you need to capture the hold image and zoom in after by using Bitmap.createBitmap an the section you want.
This is not strongly related answer. I know.
But I'd like to say that Samsung 4.2.2 has many defective issues.
It has ClipboardManager crash, ActionBar AppCompat crash, and so on.
Just filter it with simple if clause and save your life.
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN_MR1 && Build.MANUFACTURER.toUpperCase().contains("SAMSUNG")){
// ignore
}else{
// your logic on the go
}
are you again start a camera preview after taking a picture?
add this camera.startPreview();
Try this
Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
camera.startPreview();
try {
} catch (Exception e) {
if (flePicture== null){
Log.d("camera", "Error creating media file, check storage permissions: " +
e.getMessage());
return;
}
}
try {
FileOutputStream fos = new FileOutputStream(flePicture);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d("camera", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("camera", "Error accessing file: " + e.getMessage());
}
}
};
It's some issue with specific type of kernel.
Try this approach.
private static final String TAG = Test.class.getSimpleName();
private boolean isPreviewStarted;
private Camera camera;
Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
// check if this needs to stop the preview
if (deviceNeedsStopPreviewToShoot()) {
stopPreview();
}
// save your image
// restart preview if needed.
startPreview();
}
};
public void startPreview() {
if (!isPreviewStarted && camera != null) {
camera.startPreview();
isPreviewStarted = true;
}
}
public void stopPreview() {
if (isPreviewStarted && camera != null) {
camera.stopPreview();
isPreviewStarted = false;
}
}
public static boolean deviceNeedsStopPreviewToShoot() {
String[] oldDevices = {"smdk4210", "aries"};
boolean needs = Arrays.asList(oldDevices).contains(Build.BOARD);
Log.e(TAG, "Device " + Build.BOARD + (needs ? " needs " : " doesn't need ") + "to stop preview");
return needs;
}

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;
}
}

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