Set a fixed focus value in the main camera (Android Studio) - java

I am developing an app for my project and I don't want my main camera to have autofocus. I want my camera to have a specific focus value that can focus on objects that are about 5-10 cm from the main camera.
Here is the code on how the CameraManager is implemented:
private String chooseCamera() {
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
for (final String cameraId : manager.getCameraIdList()) {
final CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
// We don't use a front facing camera in this sample.
final Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
continue;
}
final StreamConfigurationMap map =
characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map == null) {
continue;
}
// Fallback to camera1 API for internal cameras that don't have full support.
// This should help with legacy situations where using the camera2 API causes
// distorted or otherwise broken previews.
useCamera2API =
(facing == CameraCharacteristics.LENS_FACING_FRONT)
|| isHardwareLevelSupported(
characteristics);
LOGGER.i("Camera API lv2?: %s", useCamera2API);
// manager.setTorchMode(cameraId, true);
return cameraId;
}
} catch (CameraAccessException e) {
LOGGER.e(e, "Not allowed to access camera");
}
return null;
}
protected void setFragment() {
String cameraId = chooseCamera();
Fragment fragment;
if (useCamera2API) {
CameraConnectionFragment camera2Fragment =
CameraConnectionFragment.newInstance(
(size, rotation) -> {
previewHeight = size.getHeight();
previewWidth = size.getWidth();
CameraActivity.this.onPreviewSizeChosen(size, rotation);
},
this,
getLayoutId(),
getDesiredPreviewFrameSize());
camera2Fragment.setCamera(cameraId);
fragment = camera2Fragment;
} else {
fragment =
new LegacyCameraConnectionFragment(this, getLayoutId(), getDesiredPreviewFrameSize());
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
}

You need to first turn off autofocus by using CaptureRequest.CONTROL_AF_MODE and then set desired focus distance value using this request key, CaptureRequest.LENS_FOCUS_DISTANCE.
To know if a device supports manual sensor or not, query characteristics and check for support.
https://developer.android.com/reference/android/hardware/camera2/CameraMetadata#REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR

Related

How to Freeze/Lock android Camera X preview with Flash Light updates on taking picture?

I am implementing Camera X. The issue i am facing is to implement a mechanism to lock/freeze camera preview when picture is captured. Currently i have implement a workaround but it doesn't work well if the flash light is on while capturing. I get a frame from previewView (PreviewView) previewView.getBitmap() as before capturing the image and then display in an captureImage (ImageView). But the the freeze frame not show flash light update. My current code is below
private void capturePhoto() {
showProgress(true);
// Get the Information to be used & stored with Image
ContentValues contentValues = getImageSaveInfo();
Uri externalUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ImageCapture.OutputFileOptions options = new ImageCapture.OutputFileOptions
.Builder(getContentResolver(), externalUri, contentValues)
.build();
// Play the Capture Sound when a picture is captured.
playCameraShutterSound();
// Display current frame From Preview in ImageView.
freezePreview(true);
imageCapture.takePicture(options,
ContextCompat.getMainExecutor(this),
new ImageCapture.OnImageSavedCallback() {
#Override
public void onImageSaved(#NonNull ImageCapture.OutputFileResults results) {
ToastUtility.successToast(getApplicationContext(),
"Photo Capture Successfully");
// Update Last Taken Image View with new Image
getLastTakenImage();
if (results.getSavedUri() != null) {
Log.d(TAG, "Image Saved At -> " + results.getSavedUri().toString());
}
showProgress(false);
freezePreview(false);
}
#Override
public void onError(#NonNull ImageCaptureException exception) {
ToastUtility.errorToast(getApplicationContext(),
"Photo Couldn't Capture");
Log.d(TAG, "Image Capture Error -> " + exception.getMessage());
showProgress(false);
freezePreview(false);
}
});
}
private void freezePreview(boolean value) {
if (value) {
Bitmap bitmap = mainBinding.previewView.getBitmap();
Glide.with(getApplicationContext())
.load(bitmap).into(mainBinding.captureImage);
mainBinding.captureImage.setVisibility(View.VISIBLE);
mainBinding.previewView.setVisibility(View.INVISIBLE);
} else {
mainBinding.previewView.setVisibility(View.VISIBLE);
mainBinding.captureImage.setVisibility(View.INVISIBLE);
}
}
The flash is triggered at some point after takePicture() is called, there isn't a callback for it in CameraX, so there isn't a direct way to know when it's fired.
You can instead use camera2 interop to indirectly check for the flash state. You can add a session CaptureCallback to ImageCapture's config, then inside the callback's onCaptureCompleted, check if the flash state of the total result is FIRED.
// Override onCaptureCompleted to check for the flash state
CameraCaptureSession.CaptureCallback sessionCaptureCallback = //... ;
// Initialize an ImageCapture builder
ImageCapture.Builder configBuilder = new ImageCapture.Builder();
// Add the session CaptureCallback to it
new Camera2Interop.Extender<>(configBuilder)
.setSessionCaptureCallback(sessionCaptureCallback);
// Build the ImageCapture use case
ImageCapture useCase = configBuilder.build();

ARCore - How to detect single horizontal plane only

I am working with ARCore in one of my project. There, I need to detect a plane and place some objects(Anchors) on it.
In my onResume function, I created a AR session and able to detect only horizontal planes using Session configuration.
#Override
protected void onResume() {
super.onResume();
if (arSceneView == null) {
return;
}
if (arSceneView.getSession() == null) {
// If the session wasn't created yet, don't resume rendering.
// This can happen if ARCore needs to be updated or permissions are not granted yet.
try {
session = DemoUtils.createArSession(this, installRequested);
mArConfig = session.getConfig();
mArConfig.setPlaneFindingMode(Config.PlaneFindingMode.HORIZONTAL);
mArConfig.setUpdateMode(Config.UpdateMode.LATEST_CAMERA_IMAGE);
session.configure(mArConfig);
if (session == null) {
installRequested = DemoUtils.hasCameraPermission(this);
return;
} else {
arSceneView.setupSession(session);
}
} catch (UnavailableException e) {
DemoUtils.handleSessionException(this, e);
}
}
try {
arSceneView.resume();
} catch (CameraNotAvailableException ex) {
DemoUtils.displayError(this, "Unable to get camera", ex);
finish();
return;
}
if (arSceneView.getSession() != null) {
try {
session.resume();
} catch (CameraNotAvailableException e) {
e.printStackTrace();
}
}
}
Here I get many horizontal planes. My requirement is to get only one horizontal plane which is detected first.
So, I tried to Disable plane finding mode in setOnUpdateListener as following,
arSceneView.getScene().setOnUpdateListener(frameTime -> {
if (loadingMessageSnackbar == null){
return;
}
Frame frame = arSceneView.getArFrame();
if (frame == null){
return;
}
if (frame.getCamera().getTrackingState() != TrackingState.TRACKING){
return;
}
for (Plane plane : frame.getUpdatedTrackables(Plane.class)){
if (plane.getTrackingState() == TrackingState.TRACKING){
Config c =arSceneView.getSession().getConfig();
c.setPlaneFindingMode(Config.PlaneFindingMode.DISABLED);
arSceneView.getSession().configure(c);
}
}
});
Here, once the plane is detected it is getting hide.
Can anyone suggest any method to get the first detected horizontal plane and place objects in that plane only??
Thanks in advance...!!
Config config = arFragment.getArSceneView().getSession().getConfig();
config.setPlaneFindingMode(Config.PlaneFindingMode.DISABLED);
arFragment.getArSceneView().getSession().configure(config);

How to turn on and off camera outside the UI thread?

I am trying to turn on and off camera flashlight using the following code, but every time I call those functions it slows down my whole app. Which is kinda annoying. Is there any way I can do it in separate thread or perhaps in a different way?
Thanks in advance.
private void turnOnFlash() {
if (!isFlashOn && hasFlash) {
if (camera == null || params == null) {
return;
}
isFlashOn = true;
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
}
}
private void turnOffFlash() {
if (isFlashOn && hasFlash) {
if (camera == null || params == null) {
return;
}
isFlashOn = false;
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
}
}
and im calling it from another function like
if (intensity[3] < 0.5f) {
turnOnFlash();
} else {
turnOffFlash();
}
setParameters and getParameters may take noticeable time.
But what really slows the app is that UI thread becomes the handler for all camera callbacks. Here in an old answer I showed how easy it is to handle the camera in a background HandlerThread.
Note that the camera API you use here was deprecated some years ago, while the current camera2 API handles this threading issue correctly, and don't need these tricks anymore.
You can post turnOffFlash() and turnOnFlash() to the same HandlerThread.

Run-time Exception Fail to connect to camera Service in Some Devices

I am using Barcode Scanner in my app. In some mobile it is giving the run-time exception Fail to connect to camera.
Here is the code I am using for Camera
/**
* Opens the camera and applies the user settings.
*
* #throws RuntimeException if the method fails
*/
#SuppressLint("InlinedApi")
private Camera createCamera() {
int requestedCameraId = getIdForRequestedCamera(mFacing);
if (requestedCameraId == -1) {
throw new RuntimeException("Could not find requested camera.");
}
Camera camera = Camera.open(requestedCameraId);
SizePair sizePair = selectSizePair(camera, mRequestedPreviewWidth, mRequestedPreviewHeight);
if (sizePair == null) {
throw new RuntimeException("Could not find suitable preview size.");
}
Size pictureSize = sizePair.pictureSize();
mPreviewSize = sizePair.previewSize();
int[] previewFpsRange = selectPreviewFpsRange(camera, mRequestedFps);
if (previewFpsRange == null) {
throw new RuntimeException("Could not find suitable preview frames per second range.");
}
Camera.Parameters parameters = camera.getParameters();
if (pictureSize != null) {
parameters.setPictureSize(pictureSize.getWidth(), pictureSize.getHeight());
}
parameters.setPreviewSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
parameters.setPreviewFpsRange(
previewFpsRange[Camera.Parameters.PREVIEW_FPS_MIN_INDEX],
previewFpsRange[Camera.Parameters.PREVIEW_FPS_MAX_INDEX]);
parameters.setPreviewFormat(ImageFormat.NV21);
setRotation(camera, parameters, requestedCameraId);
if (mFocusMode != null) {
if (parameters.getSupportedFocusModes().contains(
mFocusMode)) {
parameters.setFocusMode(mFocusMode);
} else {
Log.i(TAG, "Camera focus mode: " + mFocusMode + " is not supported on this device.");
}
}
// setting mFocusMode to the one set in the params
mFocusMode = parameters.getFocusMode();
if (mFlashMode != null) {
if (parameters.getSupportedFlashModes() != null) {
if (parameters.getSupportedFlashModes().contains(
mFlashMode)) {
parameters.setFlashMode(mFlashMode);
} else {
Log.i(TAG, "Camera flash mode: " + mFlashMode + " is not supported on this device.");
}
}
}
// setting mFlashMode to the one set in the params
mFlashMode = parameters.getFlashMode();
camera.setParameters(parameters);
// Four frame buffers are needed for working with the camera:
//
// one for the frame that is currently being executed upon in doing detection
// one for the next pending frame to process immediately upon completing detection
// two for the frames that the camera uses to populate future preview images
camera.setPreviewCallbackWithBuffer(new CameraPreviewCallback());
camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize));
camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize));
camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize));
camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize));
return camera;
}
* Stops the camera.
*/
#Override
protected void onPause() {
super.onPause();
if (mPreview != null) {
mPreview.stop();
}
}
/**
* Releases the resources associated with the camera source, the associated detectors, and the
* rest of the processing pipeline.
*/
#Override
protected void onDestroy() {
super.onDestroy();
if (mPreview != null) {
mPreview.release();
}
}
/**
* Restarts the camera.
*/
#Override
protected void onResume() {
super.onResume();
startCameraSource();
}
The run time exception I am getting is
java.lang.RuntimeException: Fail to connect to camera service
at android.hardware.Camera.<init>(Camera.java:532)
at android.hardware.Camera.open(Camera.java:360)
Any help Regarding this issue because in some devices it is working but in some it is not working I am not able to get the issue.
Always check if the camera is available or not before accesing it.
private Camera mCamera;
/**
* Opens the camera and applies the user settings.
*
* #throws RuntimeException if the method fails
*/
#SuppressLint("InlinedApi")
private Camera createCamera() {
int requestedCameraId = getIdForRequestedCamera(mFacing);
if (requestedCameraId == -1) {
throw new RuntimeException("Could not find requested camera.");
}
if (mCamera != null){
mCamera.release();
mCamera = null;
}
mCamera= Camera.open(requestedCameraId);
if(camera == null){
Toast.makeText(mContext, "Camera service is not available currently.", Toast.LENGTH_LONG.show())
}
//....
}
}
And relsease the camera before onDestroy().
/**
* Releases the resources associated with the camera source, the associated detectors, and the
* rest of the processing pipeline.
*/
#Override
protected void onDestroy() {
super.onDestroy();
if (mPreview != null) {
mPreview.release();
mCamera.release();
mCamera = null;
}

Enabling Camera Flash While Recording Video

I need a way to control the camera flash on an Android device while it is recording video. I'm making a strobe light app, and taking videos with a flashing strobe light would result in the ability to record objects that are moving at high speeds, like a fan blade.
The flash can only be enabled by starting a video preview and setting FLASH_MODE_TORCH in the camera's parameters. That would look like this:
Camera c = Camera.open();
Camera.Parameters p = c.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
c.setParameters(p);
c.startPreview();
Once the preview has started, I can flip that parameter back and forth to turn the light on and off. This works well until I try to record a video. The trouble is that in order to give the camera to the MediaRecorder, I first have to unlock it.
MediaRecorder m = new MediaRecorder();
c.unlock(); // the killer
m.setCamera(c);
After that unlock, I can no longer change the camera parameters and therefore have no way to change the flash state.
I do not know if it is actually possible to do this since I'm not the best at java-hacking, but here is what I do know:
Camera.unlock() is a native method, so I can't really see the mechanism behind the way it locks me out
Camera.Parameter has a HashMap that contains all of its parameters
Camera.setParameters(Parameters) takes the HashMap, converts it to a string, and passes it to a native method
I can eliminate all the parameters but TORCH-MODE from the HashMap and the Camera will still accept it
So, I can still access the Camera, but it won't listen to anything I tell it. (Which is kind of the purpose of Camera.unlock())
Edit:
After examining the native code, I can see that in CameraService.cpp my calls to Camera.setParameters(Parameters) get rejected because my Process ID does not match the Process ID the camera service has on record. So it would appear that that is my hurdle.
Edit2:
It would appear that the MediaPlayerService is the primary service that takes control of the camera when a video is recording. I do not know if it is possible, but if I could somehow start that service in my own process, I should be able to skip the Camera.unlock() call.
Edit3:
One last option would be if I could somehow get a pointer to the CameraHardwareInterface. From the looks of it, this is a device specific interface and probably does not include the PID checks. The main problem with this though is that the only place that I can find a pointer to it is in CameraService, and CameraService isn't talking.
Edit4: (several months later)
At this point, I don't think it is possible to do what I originally wanted. I don't want to delete the question on the off chance that someone does answer it, but I'm not actively seeking an answer. (Though, receiving a valid answer would be awesome.)
I encountered a similar issue. The user should be able to change the flash mode during recording to meet their needs depending on the light situation. After some investigative research i came to the following solution:
I assume, that you've already set up a proper SurfaceView and a SurfaceHolder with its necessary callbacks. The first thing i did was providing this code (not declared variables are globals):
public void surfaceCreated(SurfaceHolder holder) {
try {
camera = Camera.open();
parameters = camera.getParameters();
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.setPreviewDisplay(holder);
camera.startPreview();
recorder = new MediaRecorder();
} catch (IOException e) {
e.printStackTrace();
}
}
My next step was initializing and preparing the recorder:
private void initialize() {
camera.unlock();
recorder.setCamera(camera);
recorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
recorder.setVideoFrameRate(20);
recorder.setOutputFile(filePath);
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
finish();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}
It's important to note, that camera.unlock() has to be called BEFORE the whole initialization process of the media recorder. That said also be aware of the proper order of each set property, otherwise you'll get an IllegalStateException when calling prepare() or start(). When it comes to recording, i do this. This will usually be triggered by a view element:
public void record(View view) {
if (recording) {
recorder.stop();
//TODO: do stuff....
recording = false;
} else {
recording = true;
initialize();
recorder.start();
}
}
So now, i finally can record properly. But what's with that flash? Last but not least, here comes the magic behind the scenes:
public void flash(View view) {
if(!recording) {
camera.lock();
}
parameters.setFlashMode(parameters.getFlashMode().equals(Parameters.FLASH_MODE_TORCH) ? Parameters.FLASH_MODE_OFF : Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
if(!recording) {
camera.unlock();
}
}
Everytime i call that method via an onClick action i can change the flash mode, even during recording. Just take care of properly locking the camera. Once the lock is aquired by the media recorder during recording, you don't have to lock/unlock the camera again. It doesn't even work. This was tested on a Samsung Galaxy S3 with Android-Version 4.1.2. Hope this approach helps.
After preparing media recorder, use camera.lock(), and then set whatever parameters you want to set to camera.
But before starting recording you need to call camera.unlock(), and after you stop media recorder you need to call camera.lock() to start preview.
Enjoy!!!
Try this.. hopefully it will work.. :)
private static Torch torch;
public Torch() {
super();
torch = this;
}
public static Torch getTorch() {
return torch;
}
private void getCamera() {
if (mCamera == null) {
try {
mCamera = Camera.open();
} catch (RuntimeException e) {
Log.e(TAG, "Camera.open() failed: " + e.getMessage());
}
}
}
public void toggleLight(View view) {
toggleLight();
}
private void toggleLight() {
if (lightOn) {
turnLightOff();
} else {
turnLightOn();
}
}
private void turnLightOn() {
if (!eulaAgreed) {
return;
}
if (mCamera == null) {
Toast.makeText(this, "Camera not found", Toast.LENGTH_LONG);
button.setBackgroundColor(COLOR_WHITE);
return;
}
lightOn = true;
Parameters parameters = mCamera.getParameters();
if (parameters == null) {
button.setBackgroundColor(COLOR_WHITE);
return;
}
List<String> flashModes = parameters.getSupportedFlashModes();
if (flashModes == null) {
button.setBackgroundColor(COLOR_WHITE);
return;
}
String flashMode = parameters.getFlashMode();
Log.i(TAG, "Flash mode: " + flashMode);
Log.i(TAG, "Flash modes: " + flashModes);
if (!Parameters.FLASH_MODE_TORCH.equals(flashMode)) {
if (flashModes.contains(Parameters.FLASH_MODE_TORCH)) {
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(parameters);
button.setBackgroundColor(COLOR_LIGHT);
startWakeLock();
} else {
Toast.makeText(this, "Flash mode (torch) not supported",
Toast.LENGTH_LONG);
button.setBackgroundColor(COLOR_WHITE);
Log.e(TAG, "FLASH_MODE_TORCH not supported");
}
}
}
private void turnLightOff() {
if (lightOn) {
button.setBackgroundColor(COLOR_DARK);
lightOn = false;
if (mCamera == null) {
return;
}
Parameters parameters = mCamera.getParameters();
if (parameters == null) {
return;
}
List<String> flashModes = parameters.getSupportedFlashModes();
String flashMode = parameters.getFlashMode();
if (flashModes == null) {
return;
}
Log.i(TAG, "Flash mode: " + flashMode);
Log.i(TAG, "Flash modes: " + flashModes);
if (!Parameters.FLASH_MODE_OFF.equals(flashMode)) {
if (flashModes.contains(Parameters.FLASH_MODE_OFF)) {
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
mCamera.setParameters(parameters);
stopWakeLock();
} else {
Log.e(TAG, "FLASH_MODE_OFF not supported");
}
}
}
}
private void startPreview() {
if (!previewOn && mCamera != null) {
mCamera.startPreview();
previewOn = true;
}
}
private void stopPreview() {
if (previewOn && mCamera != null) {
mCamera.stopPreview();
previewOn = false;
}
}
private void startWakeLock() {
if (wakeLock == null) {
Log.d(TAG, "wakeLock is null, getting a new WakeLock");
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
Log.d(TAG, "PowerManager acquired");
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKE_LOCK_TAG);
Log.d(TAG, "WakeLock set");
}
wakeLock.acquire();
Log.d(TAG, "WakeLock acquired");
}
private void stopWakeLock() {
if (wakeLock != null) {
wakeLock.release();
Log.d(TAG, "WakeLock released");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Eula.show(this)) {
eulaAgreed = true;
}
setContentView(R.layout.main);
button = findViewById(R.id.button);
surfaceView = (SurfaceView) this.findViewById(R.id.surfaceview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
disablePhoneSleep();
Log.i(TAG, "onCreate");
}
To access the device camera, you must declare the CAMERA permission in your Android Manifest. Also be sure to include the <uses-feature> manifest element to declare camera features used by your application. For example, if you use the camera and auto-focus feature, your Manifest should include the following:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
A sample that checks for torch support might look something like this:
//Create camera and parameter objects
private Camera mCamera;
private Camera.Parameters mParameters;
private boolean mbTorchEnabled = false;
//... later in a click handler or other location, assuming that the mCamera object has already been instantiated with Camera.open()
mParameters = mCamera.getParameters();
//Get supported flash modes
List flashModes = mParameters.getSupportedFlashModes ();
//Make sure that torch mode is supported
//EDIT - wrong and dangerous to check for torch support this way
//if(flashModes != null && flashModes.contains("torch")){
if(flashModes != null && flashModes.contains(Camera.Parameters.FLASH_MODE_TORCH)){
if(mbTorchEnabled){
//Set the flash parameter to off
mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
}
else{
//Set the flash parameter to use the torch
mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
}
//Commit the camera parameters
mCamera.setParameters(mParameters);
mbTorchEnabled = !mbTorchEnabled;
}
To turn the torch on, you simply set the camera parameter Camera.Parameters.FLASH_MODE_TORCH
Camera mCamera;
Camera.Parameters mParameters;
//Get a reference to the camera/parameters
mCamera = Camera.open();
mParameters = mCamera.getParameters();
//Set the torch parameter
mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
//Comit camera parameters
mCamera.setParameters(mParameters);
To turn the torch off, set Camera.Parameters.FLASH_MODE_OFF

Categories

Resources