CameraController
public
abstract
class
CameraController
extends Object
java.lang.Object | |
↳ | androidx.camera.view.CameraController |
The abstract base camera controller class.
This a high level controller that provides most of the CameraX core features
in a single class. It handles camera initialization, creates and configures UseCase
s.
It also listens to device motion sensor and set the target rotation for the use cases.
The controller is required to be used with a PreviewView
. PreviewView
provides the UI elements to display camera preview. The layout of the PreviewView
is
used to set the crop rect so the output from other use cases matches the preview display in a
WYSIWYG way. The controller also listens to PreviewView
's touch events to handle
tap-to-focus and pinch-to-zoom features.
This class provides features of 4 UseCase
s: Preview
, ImageCapture
,
ImageAnalysis
and an experimental video capture. Preview
is required and always
enabled. ImageCapture
and ImageAnalysis
are enabled by default. The video
capture feature is experimental. It's disabled by default because it might conflict with other
use cases, especially on lower end devices. It might be necessary to disable ImageCapture
and/or ImageAnalysis
before the video capture feature can be enabled. Disabling/enabling
UseCase
s freezes the preview for a short period of time. To avoid the glitch, the
UseCase
s need to be enabled/disabled before the controller is set on PreviewView
.
Summary
Constants | |
---|---|
int |
IMAGE_ANALYSIS
Bitmask option to enable |
int |
IMAGE_CAPTURE
Bitmask option to enable |
int |
VIDEO_CAPTURE
Bitmask option to enable video capture use case. |
Public methods | |
---|---|
void
|
clearImageAnalysisAnalyzer()
Removes a previously set analyzer. |
ListenableFuture<Void>
|
enableTorch(boolean torchEnabled)
Enable the torch or disable the torch. |
CameraInfo
|
getCameraInfo()
Gets the |
CameraSelector
|
getCameraSelector()
Gets the |
int
|
getImageAnalysisBackpressureStrategy()
Returns the mode with which images are acquired. |
int
|
getImageAnalysisImageQueueDepth()
Gets the image queue depth of |
int
|
getImageCaptureFlashMode()
Gets the flash mode for |
ListenableFuture<Void>
|
getInitializationFuture()
Gets a |
LiveData<Integer>
|
getTorchState()
Returns a |
LiveData<ZoomState>
|
getZoomState()
|
boolean
|
hasCamera(CameraSelector cameraSelector)
Checks if the given |
boolean
|
isImageAnalysisEnabled()
Checks if |
boolean
|
isImageCaptureEnabled()
Checks if |
boolean
|
isPinchToZoomEnabled()
Returns whether pinch-to-zoom is enabled. |
boolean
|
isRecording()
Returns whether there is a in progress video recording. |
boolean
|
isTapToFocusEnabled()
Returns whether tap-to-focus is enabled. |
boolean
|
isVideoCaptureEnabled()
Checks if video capture is enabled. |
void
|
setCameraSelector(CameraSelector cameraSelector)
Sets the |
void
|
setEnabledUseCases(int enabledUseCases)
Enables or disables use cases. |
void
|
setImageAnalysisAnalyzer(Executor executor, ImageAnalysis.Analyzer analyzer)
Sets an analyzer to receive and analyze images. |
void
|
setImageAnalysisBackpressureStrategy(int strategy)
Sets the backpressure strategy to apply to the image producer to deal with scenarios where images may be produced faster than they can be analyzed. |
void
|
setImageAnalysisImageQueueDepth(int depth)
Sets the image queue depth of |
void
|
setImageCaptureFlashMode(int flashMode)
Sets the flash mode for |
ListenableFuture<Void>
|
setLinearZoom(float linearZoom)
Sets current zoom by a linear zoom value ranging from 0f to 1.0f. |
void
|
setPinchToZoomEnabled(boolean enabled)
Enables/disables pinch-to-zoom. |
void
|
setTapToFocusEnabled(boolean enabled)
Enables/disables tap-to-focus. |
ListenableFuture<Void>
|
setZoomRatio(float zoomRatio)
Sets current zoom by ratio. |
void
|
startRecording(OutputFileOptions outputFileOptions, Executor executor, OnVideoSavedCallback callback)
Takes a video and calls the OnVideoSavedCallback when done. |
void
|
stopRecording()
Stops a in progress video recording. |
void
|
takePicture(ImageCapture.OutputFileOptions outputFileOptions, Executor executor, ImageCapture.OnImageSavedCallback imageSavedCallback)
Captures a new still image and saves to a file along with application specified metadata. |
void
|
takePicture(Executor executor, ImageCapture.OnImageCapturedCallback callback)
Captures a new still image for in memory access. |
Inherited methods | |
---|---|
Constants
IMAGE_ANALYSIS
public static final int IMAGE_ANALYSIS
Bitmask option to enable ImageAnalysis
. In setEnabledUseCases(int)
, if
(enabledUseCases & IMAGE_ANALYSIS) != 0, then controller will enable image analysis features.
Constant Value: 2 (0x00000002)
IMAGE_CAPTURE
public static final int IMAGE_CAPTURE
Bitmask option to enable ImageCapture
. In setEnabledUseCases(int)
, if
(enabledUseCases & IMAGE_CAPTURE) != 0, then controller will enable image capture features.
Constant Value: 1 (0x00000001)
VIDEO_CAPTURE
public static final int VIDEO_CAPTURE
Bitmask option to enable video capture use case. In setEnabledUseCases(int)
, if
(enabledUseCases & VIDEO_CAPTURE) != 0, then controller will enable video capture features.
Constant Value: 4 (0x00000004)
Public methods
clearImageAnalysisAnalyzer
public void clearImageAnalysisAnalyzer ()
Removes a previously set analyzer.
This will stop data from streaming to the ImageAnalysis
.
See also:
enableTorch
public ListenableFuture<Void> enableTorch (boolean torchEnabled)
Enable the torch or disable the torch.
No-ops if the camera is not ready. The ListenableFuture
completes successfully
in this case.
Parameters | |
---|---|
torchEnabled |
boolean : true to turn on the torch, false to turn it off. |
Returns | |
---|---|
ListenableFuture<Void> |
A ListenableFuture which is successful when the torch was changed to the
value specified. It fails when it is unable to change the torch state. Cancellation of
this future is a no-op. |
See also:
getCameraInfo
public CameraInfo getCameraInfo ()
Gets the CameraInfo
of the currently attached camera.
Returns | |
---|---|
CameraInfo |
the CameraInfo of the current camera. Returns null if camera is not ready. |
See also:
getCameraSelector
public CameraSelector getCameraSelector ()
Gets the CameraSelector
.
The default value isCameraSelector.DEFAULT_BACK_CAMERA
.
Returns | |
---|---|
CameraSelector |
See also:
getImageAnalysisBackpressureStrategy
public int getImageAnalysisBackpressureStrategy ()
Returns the mode with which images are acquired.
If not set, it defaults to ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST
.
Returns | |
---|---|
int |
The backpressure strategy applied to the image producer. |
See also:
getImageAnalysisImageQueueDepth
public int getImageAnalysisImageQueueDepth ()
Gets the image queue depth of ImageAnalysis
.
Returns | |
---|---|
int |
See also:
getImageCaptureFlashMode
public int getImageCaptureFlashMode ()
Gets the flash mode for ImageCapture
.
Returns | |
---|---|
int |
the flashMode. Value is ImageCapture.FLASH_MODE_AUTO ,
ImageCapture.FLASH_MODE_ON , or ImageCapture.FLASH_MODE_OFF . |
See also:
getInitializationFuture
public ListenableFuture<Void> getInitializationFuture ()
Gets a ListenableFuture
that completes when camera initialization completes.
This future may fail with an InitializationException
and associated cause that
can be retrieved by {@link Throwable#getCause()). The cause will be a
{@link CameraUnavailableException} if it fails to access any camera during initialization.
In the rare case that the future fails with {@link CameraUnavailableException}, the camera will become unusable. This could happen for various reasons, for example hardware failure or the camera being held by another process. If the failure is temporary, killing and restarting the app might fix the issue.
The initialization also try to bind use cases before completing the {@link ListenableFuture}. The {@link ListenableFuture} will complete successfully regardless of whether the use cases are ready to be bound, e.g. it will complete successfully even if the controller is not set on a {@link PreviewView}. However the {@link ListenableFuture} will fail if the enabled use cases are not supported by the current camera.
Returns | |
---|---|
ListenableFuture<Void> |
getTorchState
public LiveData<Integer> getTorchState ()
Returns a LiveData
of current TorchState
.
The torch can be turned on and off via enableTorch(boolean)
which
will trigger the change event to the returned LiveData
.
Returns | |
---|---|
LiveData<Integer> |
a LiveData containing current torch state. |
See also:
getZoomState
public LiveData<ZoomState> getZoomState ()
Returns a LiveData
of ZoomState
.
The LiveData will be updated whenever the set zoom state has been changed. This can
occur when the application updates the zoom via setZoomRatio(float)
or setLinearZoom(float)
. The zoom state can also change anytime a
camera starts up, for example when setCameraSelector(CameraSelector)
is called.
Returns | |
---|---|
LiveData<ZoomState> |
See also:
hasCamera
public boolean hasCamera (CameraSelector cameraSelector)
Checks if the given CameraSelector
can be resolved to a camera.
Use this method to check if the device has the given camera.
Only call this method after camera is initialized. e.g. after the
ListenableFuture
from getInitializationFuture()
is finished. Calling it
prematurely throws IllegalStateException
. Example:
controller.getInitializationFuture().addListener(() -> {
if (controller.hasCamera(cameraSelector)) {
controller.setCameraSelector(cameraSelector);
} else {
// Update UI if the camera is not available.
}
// Attach PreviewView after we know the camera is available.
previewView.setController(controller);
}, ContextCompat.getMainExecutor(requireContext()));
Parameters | |
---|---|
cameraSelector |
CameraSelector |
Returns | |
---|---|
boolean |
true if the CameraSelector can be resolved to a camera. |
Throws | |
---|---|
IllegalStateException |
if the camera is not initialized. |
isImageAnalysisEnabled
public boolean isImageAnalysisEnabled ()
Checks if ImageAnalysis
is enabled.
Returns | |
---|---|
boolean |
See also:
isImageCaptureEnabled
public boolean isImageCaptureEnabled ()
Checks if ImageCapture
is enabled.
ImageCapture
is enabled by default. It has to be enabled before
takePicture(ImageCapture.OutputFileOptions, Executor, ImageCapture.OnImageSavedCallback)
can be called.
Returns | |
---|---|
boolean |
See also:
isPinchToZoomEnabled
public boolean isPinchToZoomEnabled ()
Returns whether pinch-to-zoom is enabled.
By default pinch-to-zoom is enabled.
Returns | |
---|---|
boolean |
True if pinch-to-zoom is enabled. |
isRecording
public boolean isRecording ()
Returns whether there is a in progress video recording.
Returns | |
---|---|
boolean |
isTapToFocusEnabled
public boolean isTapToFocusEnabled ()
Returns whether tap-to-focus is enabled.
By default tap-to-focus is enabled.
Returns | |
---|---|
boolean |
True if tap-to-focus is enabled. |
isVideoCaptureEnabled
public boolean isVideoCaptureEnabled ()
Checks if video capture is enabled.
Video capture is disabled by default. It has to be enabled before
startRecording(OutputFileOptions, Executor, OnVideoSavedCallback)
can be called.
Returns | |
---|---|
boolean |
setCameraSelector
public void setCameraSelector (CameraSelector cameraSelector)
Sets the CameraSelector
.
Calling this method with a CameraSelector
that resolves to a different camera
will change the camera being used by the controller. If camera initialization is complete,
the controller will immediately rebind use cases with the new CameraSelector
;
otherwise, the new CameraSelector
will be used when the camera becomes ready.
The default value is CameraSelector.DEFAULT_BACK_CAMERA
.
Parameters | |
---|---|
cameraSelector |
CameraSelector |
Throws | |
---|---|
IllegalStateException |
If the provided camera selector is unable to resolve a camera to be used for the enabled use cases. |
See also:
setEnabledUseCases
public void setEnabledUseCases (int enabledUseCases)
Enables or disables use cases.
Use cases need to be enabled before they can be used. By default, IMAGE_CAPTURE
and IMAGE_ANALYSIS
are enabled, and VIDEO_CAPTURE
is disabled. This is
necessary because VIDEO_CAPTURE
is an experimental feature that might not work
with other use cases, especially on lower end devices. When that happens, this method will
fail with an IllegalStateException
.
To make sure VIDEO_CAPTURE
works, IMAGE_CAPTURE
and
IMAGE_ANALYSIS
needs to be disabled when enabling VIDEO_CAPTURE
. For
example:
// By default, image capture is enabled. Taking picture works.
controller.takePicture(...);
// Switch to video capture to shoot video.
controller.setEnabledUseCases(VIDEO_CAPTURE);
controller.startRecording(...);
controller.stopRecording(...);
// Switch back to image capture and image analysis before taking another picture.
controller.setEnabledUseCases(IMAGE_CAPTURE|IMAGE_ANALYSIS);
controller.takePicture(...);
Parameters | |
---|---|
enabledUseCases |
int : one or more of the following use cases, bitwise-OR-ed together:
IMAGE_CAPTURE , IMAGE_ANALYSIS and/or
VIDEO_CAPTURE . |
Throws | |
---|---|
IllegalStateException |
If the current camera selector is unable to resolve a camera to be used for the enabled use cases. |
See also:
setImageAnalysisAnalyzer
public void setImageAnalysisAnalyzer (Executor executor, ImageAnalysis.Analyzer analyzer)
Sets an analyzer to receive and analyze images.
Applications can process or copy the image by implementing the
ImageAnalysis.Analyzer
. The image needs to be closed by calling
ImageProxy.close()
when the analyzing is done.
Setting an analyzer function replaces any previous analyzer. Only one analyzer can be set at any time.
Parameters | |
---|---|
executor |
Executor : The executor in which the
ImageAnalysis.Analyzer.analyze(ImageProxy) will be run. |
analyzer |
ImageAnalysis.Analyzer : of the images. |
setImageAnalysisBackpressureStrategy
public void setImageAnalysisBackpressureStrategy (int strategy)
Sets the backpressure strategy to apply to the image producer to deal with scenarios where images may be produced faster than they can be analyzed.
The available values are ImageAnalysis.STRATEGY_BLOCK_PRODUCER
and
ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST
. If not set, the backpressure strategy
will default to ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST
.
Parameters | |
---|---|
strategy |
int : The strategy to use. |
setImageAnalysisImageQueueDepth
public void setImageAnalysisImageQueueDepth (int depth)
Sets the image queue depth of ImageAnalysis
.
This sets the number of images available in parallel to ImageAnalysis.Analyzer
. The value is only used if the backpressure strategy is
ImageAnalysis.STRATEGY_BLOCK_PRODUCER
.
Parameters | |
---|---|
depth |
int : The total number of images available. |
setImageCaptureFlashMode
public void setImageCaptureFlashMode (int flashMode)
Sets the flash mode for ImageCapture
.
If not set, the flash mode will default to ImageCapture.FLASH_MODE_OFF
.
Parameters | |
---|---|
flashMode |
int : the flash mode for ImageCapture .
|
setLinearZoom
public ListenableFuture<Void> setLinearZoom (float linearZoom)
Sets current zoom by a linear zoom value ranging from 0f to 1.0f.
LinearZoom 0f represents the minimum zoom while linearZoom 1.0f represents the maximum
zoom. The advantage of linearZoom is that it ensures the field of view (FOV) varies
linearly with the linearZoom value, for use with slider UI elements (while
setZoomRatio(float)
works well for pinch-zoom gestures).
No-ops if the camera is not ready. The ListenableFuture
completes successfully
in this case.
Parameters | |
---|---|
linearZoom |
float Value is between 0.0 and 1.0 inclusive. |
Returns | |
---|---|
ListenableFuture<Void> |
a ListenableFuture which is finished when camera is set to the given ratio.
It fails with CameraControl.OperationCanceledException if there is newer value
being set or camera is closed. If the ratio is out of range, it fails with
IllegalArgumentException . Cancellation of this future is a no-op. |
See also:
setPinchToZoomEnabled
public void setPinchToZoomEnabled (boolean enabled)
Enables/disables pinch-to-zoom.
Once enabled, end user can pinch on the PreviewView
to zoom in/out if the bound
camera supports zooming.
Parameters | |
---|---|
enabled |
boolean : True to enable pinch-to-zoom.
|
setTapToFocusEnabled
public void setTapToFocusEnabled (boolean enabled)
Enables/disables tap-to-focus.
Once enabled, end user can tap on the PreviewView
to set focus point.
Parameters | |
---|---|
enabled |
boolean : True to enable tap-to-focus.
|
setZoomRatio
public ListenableFuture<Void> setZoomRatio (float zoomRatio)
Sets current zoom by ratio.
Valid zoom values range from ZoomState.getMinZoomRatio()
to
ZoomState.getMaxZoomRatio()
.
No-ops if the camera is not ready. The ListenableFuture
completes successfully
in this case.
Parameters | |
---|---|
zoomRatio |
float : The requested zoom ratio. |
Returns | |
---|---|
ListenableFuture<Void> |
a ListenableFuture which is finished when camera is set to the given ratio.
It fails with CameraControl.OperationCanceledException if there is newer value
being set or camera is closed. If the ratio is out of range, it fails with
IllegalArgumentException . Cancellation of this future is a no-op. |
startRecording
public void startRecording (OutputFileOptions outputFileOptions, Executor executor, OnVideoSavedCallback callback)
Takes a video and calls the OnVideoSavedCallback when done.
Parameters | |
---|---|
outputFileOptions |
OutputFileOptions : Options to store the newly captured video. |
executor |
Executor : The executor in which the callback methods will be run. |
callback |
OnVideoSavedCallback : Callback which will receive success or failure.
|
stopRecording
public void stopRecording ()
Stops a in progress video recording.
takePicture
public void takePicture (ImageCapture.OutputFileOptions outputFileOptions, Executor executor, ImageCapture.OnImageSavedCallback imageSavedCallback)
Captures a new still image and saves to a file along with application specified metadata.
The callback will be called only once for every invocation of this method.
By default, the saved image is mirrored to match the output of the preview if front
camera is used. To override this behavior, the app needs to explicitly set the flag to
false
using ImageCapture.Metadata.setReversedHorizontal(boolean)
and
OutputFileOptions.Builder.setMetadata(Metadata)
.
Parameters | |
---|---|
outputFileOptions |
ImageCapture.OutputFileOptions : Options to store the newly captured image. |
executor |
Executor : The executor in which the callback methods will be run. |
imageSavedCallback |
ImageCapture.OnImageSavedCallback : Callback to be called for the newly captured image. |
takePicture
public void takePicture (Executor executor, ImageCapture.OnImageCapturedCallback callback)
Captures a new still image for in memory access.
The listener is responsible for calling ImageProxy.close()
on the returned image.
Parameters | |
---|---|
executor |
Executor : The executor in which the callback methods will be run. |
callback |
ImageCapture.OnImageCapturedCallback : Callback to be invoked for the newly captured image |