Is it possible to switch between on and off multiple times in a short time the camera flashlight of an Android device? If so, how?
I am trying to create an app that is able to send data over the flashlight blinks.
To do it in code, use this link.
Basically you use the camera flash in the following manner:
private Camera camera;
Parameters params;
private void turnOnFlash() {
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
}
}
Related
I am creating a basic camera app as a small project I'm doing to get started with Android development.
When I click on the button to take a picture, there is about a 1-second delay in which the preview freezes before unfreezing again. There is no issue with crashing - just the freezing issue. Why is this happening and how can I fix it?
Below is the method where the camera is instantiated, as well as my SurfaceView class.
private void startCamera() {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cameraPreviewLayout = (FrameLayout) findViewById(R.id.camera_preview);
camera = checkDeviceCamera();
camera.setDisplayOrientation(90);
mImageSurfaceView = new ImageSurfaceView(MainActivity.this, camera);
cameraPreviewLayout.addView(mImageSurfaceView);
ImageButton captureButton = (ImageButton)findViewById(R.id.imageButton);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
camera.takePicture(null, null, pictureCallback);
camera.stopPreview();
camera.startPreview();
}
});
}
public class ImageSurfaceView extends SurfaceView implements
SurfaceHolder.Callback {
private Camera camera;
private SurfaceHolder surfaceHolder;
public ImageSurfaceView(Context context, Camera camera) {
super(context);
this.camera = camera;
this.surfaceHolder = getHolder();
this.surfaceHolder.addCallback(this);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
this.camera.setPreviewDisplay(holder);
this.camera.startPreview();
this.camera.setDisplayOrientation(90);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
}
EDIT: There is currently nothing in the pictureCallback.
Camera.PictureCallback pictureCallback = new Camera.PictureCallback() {
}
You don't need to call stopPreview() after takePicture(). And you don't need startPreview() on the next line. You do need startPreview() inside your onPictureTaken() callback (not in onClick() as in the posted code!!) if you want live preview to restart after the picture is captured into a Jpeg stream.
To keep your UI responsive while using camera, you should do all work with the camera on a background thread. But it is not enough to call Camera.open() or Camera.close() on some background thread. You must create a Handler thread and use it for Camera.open(). The same Looper will be used for all camera callbacks, including PictureCallback.onPictureTaken(). See my detailed walkthrough about the use of HandlerThread.
As I explained elsewhere, you can achieve even better performance if you use the new camera2 API on devices that fully support this API (but better use the old API with devices that provide only LEGACY level of camera2 support).
But if you want to get maximum from the camera ISP, this kind of freeze may be inevitable (this depends on many hardware and firmware design choices, made by the manufacturer). Some clever UI tweaks may help to conceal this effect.
You’ll need to enable access to the hidden “Developer options” menu on
your Android phone. To do that, simply tap the “About phone” option in
Settings. Then tap “Build number” seven times and you’re done. Now you
can just back out to the main Settings menu and you’ll find Developer
options somewhere near the bottom of the list.
==>Now that you’re done with that part, let the real fun begins. Tap the new Developer options menu you just enabled and scroll until you
see the following three settings (note that they may be located within
an “Advanced” subsection):
Window animation scale Transition animation scale Animator animation
scale
==>Did you see them? By default, each of those three options is set to “1x” but tapping them and changing them to “.5x” will dramatically
speed up your phone. This harmless tweak forces the device to speed up
all transition animations, and the entire user experience is faster
and smoother as a result
I'm trying to make a simple button that will turn on/off the device flashlight. I don't understand why android.hardware.camera is obsolete. What do I have to do in order to make my code working on all devices and also ones with older version of Android?
This is my code:
if (IsFlashlightOn)
{
if (getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH))
{
cam = Camera.open();
Camera.Parameters p = cam.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
}
else
{
try
{
cam.stopPreview();
cam.release();
cam = null;
}
catch (Exception ex)
{
// Ignore the exception
}
}
}
There is a mistake in the logic of your code. It's not related to any specific Android version. You are checking if the device has camera flashlight and then, turns it on. In the else block you are turning the camera flashlight off in the case when a device has no camera flashlight what will never happen if your device actually has a flashlight.
I think the code should look like below. It will toggle flashlight (turn it on, when it's turned off and turn it off when it's turned on).
boolean isFlashlightOn = false;
boolean deviceHasCameraFlash = getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH);
if(deviceHasCameraFlash) {
Camera camera = Camera.open();
Camera.Parameters parameters = camera.getParameters();
if(isFlashlightOn) {
// turn the flashlight off
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.stopPreview();
isFlashlightOn = false;
} else {
// turn the flashlight on
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
isFlashlightOn = true;
}
}
I couldn't test this code right now, but I think it should work, you should get the general idea now and adjust it to your purposes.
To avoid warnings in the IDE and Static Code Analysis tools, you need to add #SuppressWarnings("deprecation") annotation to the deprecated code. We need to keep it in order to have backward compatibility with older Android versions.
If you want to handle Camera on both new and old Android versions, you should prepare the separate code for these versions.
According to the documentation:
We recommend using the new android.hardware.camera2 API for new
applications.
It means you should do it in the following way:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// code for lollipop devices or newer
} else {
// code for pre-lollipop devices
}
Code for toggling flashlight with the new API would look as follows:
private void toggleFlashLight(boolean isFlashlightOn) {
CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String cameraId = camManager.getCameraIdList()[0]; // Usually front camera is at 0 position.
camManager.setTorchMode(cameraId, isFlashlightOn);
}
Moreover, check out these StackOverflow threads:
Android camera android.hardware.Camera deprecated
Android Turn on/off Camera Flash Programatically with Camera2
They may be helpful while dealing with your issue.
Regards
Please read the question before marking this as a duplicate. I'm trying to access the LED/Flashlight WITHOUT using the Camera methods shown in other code on this site. Thank you.
I'm trying to use the flashlight/torch in Android. I have found and implemented code that works for doing this. The problem I have is that I'm using an image recognition API that uses the camera as an image scanner and they don't have a light on/off function. When I try to override their methods and use the Camera methods to turn the torch on/off, this works, however, the Camera methods now control the window and their Scanner no longer has priority on the screen.
So what I'm trying to determine is... Is there another way to turn on the flashlight/torch without using the Camera methods and preview functions. Anyone have an idea how to bypass the Camera to use the flashlight/torch? Any information would be greatly appreciated.
Here is the code that I currently use, which is working to turn the flashlight on/off, but like I said...this overrides the scanner, and I need the camera/scanner to operate at the same time to recognize my images.
public class Flashlight extends AutoScannerSession {
Camera cam;
private CameraManager mCameraManager;
private Context context;
private Scanner scanner;
private AutoScannerSession.Listener listener;
private boolean advancedListener = false;
public Flashlight(Activity parent, Scanner scanner, Listener listener, SurfaceView preview) {
super(parent, scanner, listener, preview);
cam = Camera.open();
cam.setErrorCallback(new Camera.ErrorCallback() {
#Override
public void onError(int error, Camera camera) {
Log.e("erro", error +"");
}
});
this.context = parent;
this.mCameraManager = new CameraManager(parent, this, preview);
this.scanner = scanner;
this.listener = listener;
if(listener instanceof AutoScannerSession.AdvancedListener) {
this.advancedListener = true;
}
}
#Override
public void start() {
super.start();
//flashOn();
}
public void flashOn() {
android.hardware.Camera.Parameters p = cam.getParameters();
p.setFlashMode(android.hardware.Camera.Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
//cam.startPreview();
}
public void flashOff() {
cam.stopPreview();
cam.release();
}
#Override
public void stop() {
super.stop();
flashOff();
}
No there is no alternative way to work with flash. But probably you can "share" the camera object with the Scanner.
At any rate, Camera.open() in Activity.onCreate() and turning on flashlight in Activity.onStart() do not look correct. To be a good citizen among other apps, your app should not obtain camera before onResume() and release it no later than onPause().
Code Snippet to turn on camera flash light.
Camera cam = Camera.open();
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
Code snippet to turn off camera led light.
cam.stopPreview();
cam.release();
I have a Symphony H20 smartphone officially running Android 4.4.2, Kernel 3.4.67, MT6582. Setting Parameters.FLASH_MODE_TORCH as a camera parameter did not work. After trying a few hours I decided to decompile its pre-installed FlashLight app. There, I found that they write 1 in file /sys/class/torch/torch/torch_level to turn on the Camera LED and 0 to turn it off.
Then I tried the same thing and voilla! It worked.
But the same technique did not work in my Winmax W800 Plus with Android 4.4.2, Kernel 3.4.67, MT6572. It even does not have a file like /sys/class/torch/torch/torch_level at all.
So I have this camera preview set up with Camera, SurfaceView and SurfaceHolder.
I have also an ImageView where I will be putting a modified version of the camera image and I want this to update lets say once every second.
All code is ready and already working when I load images from "res" but I have a really hard time reading the image data from the camera.
I've tried following already:
Creating an intent for MediaStore.ACTION_IMAGE_CAPTURE and starting an onActivityResult getting a small thumbnail (enough for me actually) from (Bitmap)data.getExtras().get("data")
The problem is that this opens the camera App and you need to "manually" take a picture.
Creating a Camera.PreviewCallback, taking the YuvImage, and converting it to an image using YuvImage.compressToJpeg(...).
The problem here is that I can't get it to start no matter when or where i put the Camera.setPreviewCallbackWithBuffer(PreviewCallback).
Try to take the data directly from PreviewHolder by locking in to the canvas using lockCanvas() and trying to convert it to a bitmap
Obviously Doesn't work.
Edit:
What is the best way to make this work? I mean QR-Code readers must read the image data out of the camera continuously, how do they work?
I went for option number 2 and finally made it work.
used this callback, forgot the #Override before
private Camera.PreviewCallback previewCallback= new Camera.PreviewCallback()
{
#Override
public void onPreviewFrame(byte[] data,Camera cam)
{
Camera.Size previewSize = cam.getParameters().getPreviewSize();
YuvImage yuvImage = new YuvImage(data, ImageFormat.NV21,previewSize.width,previewSize.height, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yuvImage.compressToJpeg(new Rect(0,0,previewSize.width,previewSize.height),80,baos);
byte[] jdata = baos.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(jdata,0,jdata.length);
}
};
And initiating it using setPreviewCallback rather than setPreviewCallbackWithBuffer
SurfaceHolder.Callback surfaceCallback=new SurfaceHolder.Callback()
{
public void surfaceCreated(SurfaceHolder holder) {
camera.setPreviewCallback(previewCallback);
}
}
I know, this question was asked maaany times, but I do not think there was a solution for this. I'm developing application which should be targeted for all devices with android system and backfacing camera. The problem is I can test application on only two devices and have to be sure that it works on all devices.I think only reasonable solution would be to to find a code samples for camera api that are quaranteed to work on nearly all devices. Does anybody can provide such sources ... but sources ... that really are tested on maaaaany (ALL) devices ? I've lost all hairs from my head ... and .. and I'm loosing my mind i think... It is all because I've released app (only for tests in my company) which was tested on only two devices, and which uses camera api in a way that should work, but it appears there are some phones like for example HTC desire HD or HTC Evo 3d (with 3d camera) where the app simply crashes (because of fu..ing camera) or freezes (also because of fu..ing camera). If there is someone who have sources for camera api (taking a picture without user gui interaction, periodically) which are really tested, please be so kind and if You can, post the source or redirect me to proper place.
Hmm maybe The question should sound like this: "Is it technically possible to use camera api on all devices ?"
Maybe I will describe how I'm currently using api.
1) Initialize cam:
public void initCam()
{
LoggingFacility.debug("Attempting to initialize camera",this);
LoggingFacility.debug("Preview is enabled:"+isPreview,this);
try {
if (camera==null)
{
camera = Camera.open();
camera.setPreviewDisplay(mHolder);
if (camera!=null)
{
Camera.Parameters parameters = camera.getParameters();
List<Size> sizes = parameters.getSupportedPictureSizes();
if (sizes!=null)
{
Size min = sizes.get(0);
for (Size size : sizes)
if (size.width<min.width) min = size;
{
parameters.setPictureSize(min.width, min.height);
}
}
camera.setParameters(parameters);
setDisplayOrientation(90);
}
}
startPreview(aps);
} catch (Throwable e){
if (exceptionsCallback!=null)
exceptionsCallback.onException(e);
}
}
2) Start preview:
private void startPreview(AfterPreviewStarted after)
{
try {
if (!isPreview)
{
LoggingFacility.debug("Starting preview",this);
//camera.stopPreview();
camera.startPreview();
isPreview = true;
LoggingFacility.debug("Preview is enabled:"+isPreview,this);
}
if (after!=null) after.doAfter();
}catch(Throwable e)
{
if (exceptionsCallback!=null)
exceptionsCallback.onException(e);
}
}
3) Take picture:
public void takePicture(final PictureCallback callback)
{
LoggingFacility.debug("Attempting to take a picture",this);
if (camera!=null)
{
if (isPreview)
{
try
{
LoggingFacility.debug("preview is enabled jut before taking picture",this);
//AudioManager mgr = (AudioManager)ctx.getSystemService(Context.AUDIO_SERVICE);
//mgr.setStreamMute(AudioManager.STREAM_SYSTEM, true);
LoggingFacility.debug("Taking picture... preview will be stopped...",this);
isPreview = false;
camera.takePicture(null, new PictureCallback(){
public void onPictureTaken(byte[] arg0, Camera arg1)
{
//LoggingFacility.debug("Picture has been taken - 1t callback",CameraPreview.this);
}
}, callback);
//mgr.setStreamMute(AudioManager.STREAM_SYSTEM, false);
} catch (Throwable e){
if (exceptionsCallback!=null)
exceptionsCallback.onException(e);
}
}
}
4) Release camera after done, or after surface is disposed.
public void releaseCam()
{
LoggingFacility.debug("Attempting to release camera",this);
if (camera!=null)
{
isTakingPictures = false;
camera.stopPreview();
isPreview = false;
camera.release();
camera = null;
LoggingFacility.debug("A camera connection has been released...",this);
}
}
In 3rd code snippet in callback method Im invoking startPreview again since after taking picture a preview is disabled, and some smartphones require preview to be started to make a picture. All above method are part of class extending SurfaceView and implementing SurfaceHolder.Callback and is a part of activity.
SurfaceHolder.Callback is implemented as follows:
public void surfaceCreated(SurfaceHolder holder) {
initCam();
}
public void surfaceDestroyed(SurfaceHolder holder) {
releaseCam();
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
}
Constructor of class
CameraPreview(Context context) {
super(context);
this.ctx = context;
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
I was also considering another approach - to overcome taking picture, and instead of this to register onPreviewFrame callback and for example in this callback check the flag if a picture has been requested, if so - convert image to bitmap and use it in further processing. I was trying this approach, but then stuck with another problem - even If I register empty callback, a gui responds much slower.
For everyone who like me have problems using android camera api please refer to this link . It seems the code from this sample works on majority of smartphones.
final int PICTURE_TAKEN = 1;
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(filename)));
startActivityForResult(intent, PICTURE_TAKEN);
This works for me, haven't had complaints sofar.