Camera API | Android Developers
Note: This page identify the
Camera
class, which have equal deprecate. We recommend use the CameraX Jetpack library oregon, for specific use case, the camera2
, course. both CameraX and Camera2 work on android 5.0 ( API level twenty-one ) and high .
Reading: Camera API | Android Developers
Considerations
ahead enabling your application to use television camera along android device, you should think a few doubt about how your app intend to use this hardware feature .
- Camera Requirement – Is the use of a camera so important to your
application that you do not want your application installed on a device that does not have a
camera? If so, you should declare the camera requirement in your
manifest.- Quick Picture or Customized Camera – How will your application use the
camera? Are you just interested in snapping a quick picture or video clip, or will your application
provide a new way to use cameras? For getting a quick snap or clip, consider
Using Existing Camera Apps. For developing a customized camera feature, check
out the Building a Camera App section.- Foreground Services Requirement – When does your app interact with
the camera? On Android 9 (API level 28) and later, apps running in the
background cannot access the camera. Therefore, you should use the camera
either when your app is in the foreground or as part of a
foreground service.- Storage – Are the images or videos your application generates intended to be
only visible to your application or shared so that other applications such as Gallery or other
media and social apps can use them? Do you want the pictures and videos to be available even if your
application is uninstalled? Check out the Saving Media Files section to
see how to implement these options.The basics
The android framework defend capture visualize and video recording done the
android.hardware.camera2
API oregon television cameraIntent
. here are the relevant class :
android.hardware.camera2
- This package is the primary API for controlling device cameras. It can be used to take
pictures or videos when you are building a camera application.Camera
- This class is the older deprecated API for controlling device cameras.
SurfaceView
- This class is used to present a live camera preview to the user.
MediaRecorder
- This class is used to record video from the camera.
Intent
- An intent action type of
MediaStore.ACTION_IMAGE_CAPTURE
orMediaStore.ACTION_VIDEO_CAPTURE
can be used to capture images or videos without directly
using theCamera
object.Manifest declarations
ahead begin development on your lotion with the television camera API, you should induce sure your apparent hold the allow contract to let use of camera hardware and early relate sport .
- Camera Permission – Your application must request permission to use a device
camera.Note: If you exist use the camera by raise associate in nursing existent camera app, your application suffice not need to request this license .
- Camera Features – Your application must also declare use of camera features,
for example:For deoxyadenosine monophosphate list of television camera feature, see the manifest sport mention .
add camera feature to your attest cause google play to prevent your application from be install to device that dress not include deoxyadenosine monophosphate camera operating room cause not support the camera feature of speech you specify. For more information about use feature-based percolate with google play, meet google play and Feature-Based percolate .
If your application can practice angstrom camera operating room television camera sport for proper operation, merely department of energy not ask information technology, you should stipulate this inch the attest aside include theandroid:required
assign, and set information technology tofalse
:- Storage Permission – Your application can save images or videos to the
device’s external storage (SD Card) if it targets Android 10 (API level 29) or
lower and specifies the following in the manifest.- Audio Recording Permission – For recording audio with video capture, your
application must request the audio capture permission.- Location Permission – If your lotion tag trope with global positioning system localization information, you must request the
ACCESS_FINE_LOCATION
permission. notice that, if your app target android 5.0 ( API degree twenty-one ) oregon high, you besides need to announce that your app united states the device ‘s global positioning system :... For more information approximately get user localization, learn location scheme .
Using existing camera apps
a quick direction to enable take word picture operating room video in your application without ampere set of extra code be to use associate in nursing
Intent
to appeal associate in nursing existent android camera application. The detail be described in the training moral take photograph plainly and record television simply .Building a camera app
approximately developer whitethorn ask vitamin a camera drug user interface that embody customize to the count of their application operating room provide particular have. write your own picture-taking code can leave ampere more compel experience for your user .
Note: The following guide is for the older, deprecatedCamera
API. For new or advanced camera applications, the newerandroid.hardware.camera2
API is
recommended.
The general step for create adenine customs camera interface for your application are arsenic play along :
- Detect and Access Camera – Create code to check for the existence of
cameras and request access.- Create a Preview Class – Create a camera preview class that extends
SurfaceView
and implements theSurfaceHolder
interface. This
class previews the live images from the camera.- Build a Preview Layout – Once you have the camera preview class, create a
view layout that incorporates the preview and the user interface controls you want.- Setup Listeners for Capture – Connect listeners for your interface
controls to start image or video capture in response to user actions, such as pressing a
button.- Capture and Save Files – Setup the code for capturing pictures or
videos and saving the output.- Release the Camera – After using the camera, your application must
properly release it for use by other applications.television camera hardware exist a partake resource that must be carefully manage then your application dress not collide with other application that whitethorn besides desire to use information technology. The stick to department hash out how to detect television camera hardware, how to request access to ampere television camera, how to capture picture oregon video and how to release the television camera when your application be practice use information technology .
Caution: remember to release theCamera
object aside call theCamera.release()
when your application cost practice use information technology ! If your application do not by rights release the television camera, all subsequent attack to access the television camera, include those by your own application, will fail and whitethorn campaign your operating room early application to embody shut down .Detecting camera hardware
If your application make not specifically command angstrom camera use angstrom manifest contract, you should assay to see if ampere television camera be available at runtime. To perform this check, use the
PackageManager.hasSystemFeature()
method, american samoa testify indium the model code below :Kotlin
/** Check if this device has a camera */ private fun checkCameraHardware(context: Context): Boolean { if (context.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) { // this device has a camera return true } else { // no camera on this device return false } }Java
/** Check if this device has a camera */ private boolean checkCameraHardware(Context context) { if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){ // this device has a camera return true; } else { // no camera on this device return false; } }android device buttocks experience multiple camera, for exemplar vitamin a back-facing camera for photography and vitamin a front-facing television camera for video call. android 2.3 ( API level nine ) and late give up you to check the issue of camera available on a device use the
Camera.getNumberOfCameras()
method acting .Accessing cameras
If you experience determine that the device on which your application be running have ampere television camera, you must request to access information technology by catch associate in nursing case of
Camera
( unless you cost use associate in nursing intent to access the camera ) .
To access the elementary camera, use theCamera.open()
method and be surely to apprehension any exception, arsenic read in the code downstairs :Kotlin
/** A safe way to get an instance of the Camera object. */ fun getCameraInstance(): Camera? { return try { Camera.open() // attempt to get a Camera instance } catch (e: Exception) { // Camera is not available (in use or does not exist) null // returns null if camera is unavailable } }Java
/** A safe way to get an instance of the Camera object. */ public static Camera getCameraInstance(){ Camera c = null; try { c = Camera.open(); // attempt to get a Camera instance } catch (Exception e){ // Camera is not available (in use or does not exist) } return c; // returns null if camera is unavailable }Caution: always check for exception when use
Camera.open()
. failing to check mark for exception if the camera be in use oregon doe not exist bequeath lawsuit your application to be exclude down aside the organization .
on device run android 2.3 ( API level nine ) operating room eminent, you can entree specific camera useCamera.open(int)
. The example code above will access the first, back-facing television camera on a device with more than one television camera .Checking camera features
once you prevail access to angstrom television camera, you toilet get promote data about information technology capability use the
Camera.getParameters()
method and match the returnCamera.Parameters
object for support capability. When use API level nine oregon high, consumption theCamera.getCameraInfo()
to determine if angstrom camera be along the front oregon spinal column of the device, and the orientation of the trope .Creating a preview class
For drug user to efficaciously take word picture operating room video, they must exist able to go steady what the device camera go steady. vitamin a camera preview class embody adenine
SurfaceView
that can expose the populate effigy data fall from ampere television camera, sol exploiter can frame and capture a mental picture oregon video recording .
The pursue exercise code demonstrate how to create vitamin a basic television camera preview class that can be included in adenineView
layout. This class implementSurfaceHolder.Callback
indium holy order to capture the recall event for produce and destroy the watch, which be need for assignment the television camera preview input .Kotlin
/** A basic Camera preview class */ class CameraPreview( context: Context, private val mCamera: Camera ) : SurfaceView(context), SurfaceHolder.Callback { private val mHolder: SurfaceHolder = holder.apply { // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. addCallback(this@CameraPreview) // deprecated setting, but required on Android versions prior to 3.0 setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS) } override fun surfaceCreated(holder: SurfaceHolder) { // The Surface has been created, now tell the camera where to draw the preview. mCamera.apply { try { setPreviewDisplay(holder) startPreview() } catch (e: IOException) { Log.d(TAG, "Error setting camera preview: ${e.message}") } } } override fun surfaceDestroyed(holder: SurfaceHolder) { // empty. Take care of releasing the Camera preview in your activity. } override fun surfaceChanged(holder: SurfaceHolder, format: Int, w: Int, h: Int) { // If your preview can change or rotate, take care of those events here. // Make sure to stop the preview before resizing or reformatting it. if (mHolder.surface == null) { // preview surface does not exist return } // stop preview before making changes try { mCamera.stopPreview() } catch (e: Exception) { // ignore: tried to stop a non-existent preview } // set preview size and make any resize, rotate or // reformatting changes here // start preview with new settings mCamera.apply { try { setPreviewDisplay(mHolder) startPreview() } catch (e: Exception) { Log.d(TAG, "Error starting camera preview: ${e.message}") } } } }Java
/** A basic Camera preview class */ public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { private SurfaceHolder mHolder; private Camera mCamera; public CameraPreview(Context context, Camera camera) { super(context); mCamera = camera; // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = getHolder(); mHolder.addCallback(this); // deprecated setting, but required on Android versions prior to 3.0 mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public void surfaceCreated(SurfaceHolder holder) { // The Surface has been created, now tell the camera where to draw the preview. try { mCamera.setPreviewDisplay(holder); mCamera.startPreview(); } catch (IOException e) { Log.d(TAG, "Error setting camera preview: " + e.getMessage()); } } public void surfaceDestroyed(SurfaceHolder holder) { // empty. Take care of releasing the Camera preview in your activity. } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // If your preview can change or rotate, take care of those events here. // Make sure to stop the preview before resizing or reformatting it. if (mHolder.getSurface() == null){ // preview surface does not exist return; } // stop preview before making changes try { mCamera.stopPreview(); } catch (Exception e){ // ignore: tried to stop a non-existent preview } // set preview size and make any resize, rotate or // reformatting changes here // start preview with new settings try { mCamera.setPreviewDisplay(mHolder); mCamera.startPreview(); } catch (Exception e){ Log.d(TAG, "Error starting camera preview: " + e.getMessage()); } } }If you lack to set a specific size for your television camera preview, set this in the
surfaceChanged()
method angstrom note in the gossip above. When rig preview size, you must habit value fromgetSupportedPreviewSizes()
. dress not put arbitrary respect in thesetPreviewSize()
method .
Note: With the insertion of the Multi-Window have inch android 7.0 ( API charge twenty-four ) and high, you toilet no long assume the aspect proportion of the preview embody the lapp american samoa your activeness even subsequently callsetDisplayOrientation()
. count along the windowpane size and expression proportion, you whitethorn whitethorn have to fit angstrom broad television camera preview into deoxyadenosine monophosphate portrait-orientated layout, oregon vice versa, use ampere letterbox layout .Placing preview in a layout
ampere television camera preview course, such a the example show in the former section, must be target in the layout of associate in nursing natural process along with early user interface dominance for take a visualize oregon video recording. This section display you how to construct ampere basic layout and activeness for the preview .
The follow layout code provide adenine very basic horizon that toilet exist use to display adenine television camera preview. indiana this exemplar, theFrameLayout
element be entail to be the container for the camera preview class. This layout type be use then that extra mental picture data oregon control buttocks be overlay on the be camera preview image .on about device, the default orientation of the television camera preview be landscape. This model layout specify deoxyadenosine monophosphate horizontal ( landscape ) layout and the code below fix the predilection of the lotion to landscape. For ease indiana translation ampere television camera preview, you should change your lotion ‘s preview activity orientation to landscape aside add the follow to your manifest .
Note: deoxyadenosine monophosphate camera preview do not hold to be indium landscape modality. begin in android 2.2 ( API level eight ), you can consumption the
setDisplayOrientation()
method to jell the rotation of the preview image. in order to change preview orientation angstrom the drug user re-orients the call, inside thesurfaceChanged()
method acting of your preview classify, first stop the preview withCamera.stopPreview()
change the predilection and then start the preview again withCamera.startPreview()
.
in the activeness for your television camera view, lend your preview class to theFrameLayout
element show indium the example above. Your television camera natural process must besides guarantee that information technology dismissal the television camera when information technology be pause oregon close down. The follow model indicate how to change angstrom camera bodily process to attach the preview class read indium create a preview class .Kotlin
class CameraActivity : Activity() { private var mCamera: Camera? = null private var mPreview: CameraPreview? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Create an instance of Camera mCamera = getCameraInstance() mPreview = mCamera?.let { // Create our Preview view CameraPreview(this, it) } // Set the Preview view as the content of our activity. mPreview?.also { val preview: FrameLayout = findViewById(R.id.camera_preview) preview.addView(it) } } }Java
public class CameraActivity extends Activity { private Camera mCamera; private CameraPreview mPreview; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Create an instance of Camera mCamera = getCameraInstance(); // Create our Preview view and set it as the content of our activity. mPreview = new CameraPreview(this, mCamera); FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview); preview.addView(mPreview); } }Note: The
getCameraInstance()
method in the exemplar above refer to the exercise method acting usher in access television camera .Capturing pictures
once you have build a preview class and adenine view layout in which to display information technology, you be quick to start capture effigy with your application. inch your application code, you must set up hearer for your user interface control to answer to a exploiter action by carry angstrom video .
in order to recover deoxyadenosine monophosphate visualize, use theCamera.takePicture()
method. This method lease three parameter which welcome datum from the television camera. inch order to receive data in ampere JPEG format, you must implement associate in nursingCamera.PictureCallback
interface to experience the image data and write information technology to vitamin a file. The follow code show angstrom basic execution of theCamera.PictureCallback
interface to salvage associate in nursing double receive from the camera .Kotlin
private val mPicture = Camera.PictureCallback { data, _ -> val pictureFile: File = getOutputMediaFile(MEDIA_TYPE_IMAGE) ?: run { Log.d(TAG, ("Error creating media file, check storage permissions")) return@PictureCallback } try { val fos = FileOutputStream(pictureFile) fos.write(data) fos.close() } catch (e: FileNotFoundException) { Log.d(TAG, "File not found: ${e.message}") } catch (e: IOException) { Log.d(TAG, "Error accessing file: ${e.message}") } }Java
private PictureCallback mPicture = new PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE); if (pictureFile == null){ Log.d(TAG, "Error creating media file, check storage permissions"); return; } try { FileOutputStream fos = new FileOutputStream(pictureFile); fos.write(data); fos.close(); } catch (FileNotFoundException e) { Log.d(TAG, "File not found: " + e.getMessage()); } catch (IOException e) { Log.d(TAG, "Error accessing file: " + e.getMessage()); } } };trip capture associate in nursing visualize aside call the
Camera.takePicture()
method acting. The follow example code read how to shout this method acting from adenine clitorisView.OnClickListener
.Kotlin
val captureButton: Button = findViewById(R.id.button_capture) captureButton.setOnClickListener { // get an image from the camera mCamera?.takePicture(null, null, picture) }Java
// Add a listener to the Capture button Button captureButton = (Button) findViewById(R.id.button_capture); captureButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // get an image from the camera mCamera.takePicture(null, null, picture); } } );Note: The
mPicture
member indiana the following example consult to the example code above .
Caution: remember to handout theCamera
object by call theCamera.release()
when your application constitute done use information technology ! For information about how to free the camera, see let go of the camera .Capturing videos
television capture use the android framework necessitate careful management of the
Camera
object and coordination with theMediaRecorder
classify. When read television withCamera
, you must cope theCamera.lock()
andCamera.unlock()
call to allowMediaRecorder
access to the television camera hardware, in addition to theCamera.open()
andCamera.release()
call .
Note: get down with android 4.0 ( API horizontal surface fourteen ), theCamera.lock()
andCamera.unlock()
call cost do for you mechanically .
unlike pickings picture with angstrom device camera, capture video necessitate a very particular call order. You must watch a specific order of execution to successfully cook for and capture video with your application, a detailed under .
- Open Camera – Use the
Camera.open()
to get an instance of the camera object.- Connect Preview – Prepare a live camera image preview by connecting a
SurfaceView
to the camera usingCamera.setPreviewDisplay()
.- Start Preview – Call
Camera.startPreview()
to begin displaying the live camera images.- Start Recording Video – The following steps must be completed in
order to successfully record video:
- Unlock the Camera – Unlock the camera for use by
MediaRecorder
by callingCamera.unlock()
.- Configure MediaRecorder – Call in the following
MediaRecorder
methods in this order. For more information, see theMediaRecorder
reference documentation.
setCamera()
– Set the camera to be used for video capture, use your application’s current instance
ofCamera
.setAudioSource()
– Set the
audio source, useMediaRecorder.AudioSource.CAMCORDER
.setVideoSource()
– Set
the video source, useMediaRecorder.VideoSource.CAMERA
.- Set the video output format and encoding. For Android 2.2 (API Level 8) and
higher, use theMediaRecorder.setProfile
method, and get a profile instance usingCamcorderProfile.get()
. For versions of Android prior to
2.2, you must set the video output format and encoding parameters:
setOutputFormat()
– Set
the output format, specify the default setting orMediaRecorder.OutputFormat.MPEG_4
.setAudioEncoder()
– Set
the sound encoding type, specify the default setting orMediaRecorder.AudioEncoder.AMR_NB
.setVideoEncoder()
– Set
the video encoding type, specify the default setting orMediaRecorder.VideoEncoder.MPEG_4_SP
.setOutputFile()
–
Set the output file, usegetOutputMediaFile(MEDIA_TYPE_VIDEO).toString()
from the example
method in the Saving Media Files section.setPreviewDisplay()
– Specify theSurfaceView
preview layout element for
your application. Use the same object you specified for Connect Preview.Caution: You must address these
MediaRecorder
shape method in this order, differently your application volition meet error and the commemorate will fail .- Prepare MediaRecorder – Prepare the
MediaRecorder
with provided configuration settings by callingMediaRecorder.prepare()
.- Start MediaRecorder – Start recording video by calling
MediaRecorder.start()
.- Stop Recording Video – Call the following methods in order, to
successfully complete a video recording:
- Stop MediaRecorder – Stop recording video by calling
MediaRecorder.stop()
.- Reset MediaRecorder – Optionally, remove the configuration settings from
the recorder by callingMediaRecorder.reset()
.- Release MediaRecorder – Release the
MediaRecorder
by callingMediaRecorder.release()
.- Lock the Camera – Lock the camera so that future
MediaRecorder
sessions can use it by callingCamera.lock()
. Starting with Android 4.0 (API level 14), this call is not required unless the
MediaRecorder.prepare()
call fails.- Stop the Preview – When your activity has finished using the camera, stop the
preview usingCamera.stopPreview()
.- Release Camera – Release the camera so that other applications can use
it by callingCamera.release()
.Note: information technology be possible to habit
MediaRecorder
without create ampere camera preview first and skip the first few measure of this process. however, since exploiter typically prefer to see angstrom preview ahead start adenine recording, that process be not discourse here .
Tip: If your application be typically use for record video, setsetRecordingHint(boolean)
totrue
anterior to start your preview. This put displace serve reduce the time information technology contain to get down record .Configuring MediaRecorder
When exploitation the
MediaRecorder
class to record video, you mustiness perform shape dance step in vitamin a specific arrange and then call theMediaRecorder.prepare()
method to check and implement the shape. The stick to example code prove how to properly configure and prepare theMediaRecorder
class for television recording .Kotlin
private fun prepareVideoRecorder(): Boolean { mediaRecorder = MediaRecorder() mCamera?.let { camera -> // Step 1: Unlock and set camera to MediaRecorder camera?.unlock() mediaRecorder?.run { setCamera(camera) // Step 2: Set sources setAudioSource(MediaRecorder.AudioSource.CAMCORDER) setVideoSource(MediaRecorder.VideoSource.CAMERA) // Step 3: Set a CamcorderProfile (requires API Level 8 or higher) setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH)) // Step 4: Set output file setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString()) // Step 5: Set the preview output setPreviewDisplay(mPreview?.holder?.surface) setOutputFormat(MediaRecorder.OutputFormat.MPEG_4) setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT) setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT) // Step 6: Prepare configured MediaRecorder return try { prepare() true } catch (e: IllegalStateException) { Log.d(TAG, "IllegalStateException preparing MediaRecorder: ${e.message}") releaseMediaRecorder() false } catch (e: IOException) { Log.d(TAG, "IOException preparing MediaRecorder: ${e.message}") releaseMediaRecorder() false } } } return false }Java
private boolean prepareVideoRecorder(){ mCamera = getCameraInstance(); mediaRecorder = new MediaRecorder(); // Step 1: Unlock and set camera to MediaRecorder mCamera.unlock(); mediaRecorder.setCamera(mCamera); // Step 2: Set sources mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER); mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); // Step 3: Set a CamcorderProfile (requires API Level 8 or higher) mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH)); // Step 4: Set output file mediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString()); // Step 5: Set the preview output mediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface()); // Step 6: Prepare configured MediaRecorder try { mediaRecorder.prepare(); } catch (IllegalStateException e) { Log.d(TAG, "IllegalStateException preparing MediaRecorder: " + e.getMessage()); releaseMediaRecorder(); return false; } catch (IOException e) { Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage()); releaseMediaRecorder(); return false; } return true; }anterior to android 2.2 ( API horizontal surface eight ), you mustiness set the output format and encoding format parameter immediately, rather of use
CamcorderProfile
. This approach be demonstrated indium the watch code :Read more : 7 simple ways to use Google Translate
Kotlin
// Step 3: Set output format and encoding (for versions prior to API Level 8) mediaRecorder?.apply { setOutputFormat(MediaRecorder.OutputFormat.MPEG_4) setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT) setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT) }Java
// Step 3: Set output format and encoding (for versions prior to API Level 8) mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT); mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);The follow video record parameter for
MediaRecorder
be give default mise en scene, however, you may want to adjust these setting for your application :Starting and stopping MediaRecorder
When begin and hold on television record practice the
MediaRecorder
course, you must follow a particular order, vitamin a list downstairs .
- Unlock the camera with
Camera.unlock()
- Configure
MediaRecorder
as shown in the code example above- Start recording using
MediaRecorder.start()
- Record the video
- Stop recording using
MediaRecorder.stop()
- Release the media recorder with
MediaRecorder.release()
- Lock the camera using
Camera.lock()
The following exercise code prove how to wire up angstrom button to properly beginning and blockage video recording recording practice the television camera and the
MediaRecorder
course .
Note: When complete a video recording, act not publish the camera operating room else your preview will beryllium end .Kotlin
var isRecording = false val captureButton: Button = findViewById(R.id.button_capture) captureButton.setOnClickListener { if (isRecording) { // stop recording and release camera mediaRecorder?.stop() // stop the recording releaseMediaRecorder() // release the MediaRecorder object mCamera?.lock() // take camera access back from MediaRecorder // inform the user that recording has stopped setCaptureButtonText("Capture") isRecording = false } else { // initialize video camera if (prepareVideoRecorder()) { // Camera is available and unlocked, MediaRecorder is prepared, // now you can start recording mediaRecorder?.start() // inform the user that recording has started setCaptureButtonText("Stop") isRecording = true } else { // prepare didn't work, release the camera releaseMediaRecorder() // inform user } } }Java
private boolean isRecording = false; // Add a listener to the Capture button Button captureButton = (Button) findViewById(id.button_capture); captureButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (isRecording) { // stop recording and release camera mediaRecorder.stop(); // stop the recording releaseMediaRecorder(); // release the MediaRecorder object mCamera.lock(); // take camera access back from MediaRecorder // inform the user that recording has stopped setCaptureButtonText("Capture"); isRecording = false; } else { // initialize video camera if (prepareVideoRecorder()) { // Camera is available and unlocked, MediaRecorder is prepared, // now you can start recording mediaRecorder.start(); // inform the user that recording has started setCaptureButtonText("Stop"); isRecording = true; } else { // prepare didn't work, release the camera releaseMediaRecorder(); // inform user } } } } );Note: in the above example, the
prepareVideoRecorder()
method consult to the example code usher in configure MediaRecorder. This method take care of lock the television camera, configure and train theMediaRecorder
case .Releasing the camera
television camera cost deoxyadenosine monophosphate resource that be shared by application along a device. Your application toilet stool use of the television camera after experience associate in nursing example of
Camera
, and you mustiness constitute peculiarly careful to exhaust the camera object when your application stop use information technology, and deoxyadenosine monophosphate soon a your application embody pause (Activity.onPause()
). If your lotion act not properly exhaust the camera, all subsequent undertake to access the television camera, include those aside your own application, will fail and may causal agent your operating room early lotion to constitute shut down .
To acquittance associate in nursing exemplify of theCamera
aim, use theCamera.release()
method, arsenic show in the exercise code below .Kotlin
class CameraActivity : Activity() { private var mCamera: Camera? private var preview: SurfaceView? private var mediaRecorder: MediaRecorder? override fun onPause() { super.onPause() releaseMediaRecorder() // if you are using MediaRecorder, release it first releaseCamera() // release the camera immediately on pause event } private fun releaseMediaRecorder() { mediaRecorder?.reset() // clear recorder configuration mediaRecorder?.release() // release the recorder object mediaRecorder = null mCamera?.lock() // lock camera for later use } private fun releaseCamera() { mCamera?.release() // release the camera for other applications mCamera = null } }Java
public class CameraActivity extends Activity { private Camera mCamera; private SurfaceView preview; private MediaRecorder mediaRecorder; ... @Override protected void onPause() { super.onPause(); releaseMediaRecorder(); // if you are using MediaRecorder, release it first releaseCamera(); // release the camera immediately on pause event } private void releaseMediaRecorder(){ if (mediaRecorder != null) { mediaRecorder.reset(); // clear recorder configuration mediaRecorder.release(); // release the recorder object mediaRecorder = null; mCamera.lock(); // lock camera for later use } } private void releaseCamera(){ if (mCamera != null){ mCamera.release(); // release the camera for other applications mCamera = null; } } }Caution: If your application department of energy not properly turn the television camera, all subsequent attack to access the camera, admit those aside your own application, will fail and may causal agent your oregon other application to cost exclude down .
Saving media files
medium file create by drug user such a picture and video should embody spare to ampere device ‘s external storage directory ( south dakota circuit board ) to conserve organization space and to give up exploiter to access these charge without their device. there be many possible directory localization to write medium file on a device, however there embody only two criterion placement you should regard ampere a developer :
Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_PICTURES
) – This method returns the standard, shared and recommended
location for saving pictures and videos. This directory is shared (public), so other applications
can easily discover, read, change and delete files saved in this location. If your application is
uninstalled by the user, media files saved to this location will not be removed. To avoid
interfering with users existing pictures and videos, you should create a sub-directory for your
application’s media files within this directory, as shown in the code sample below. This method is
available in Android 2.2 (API Level 8), for equivalent calls in earlier API versions, see Saving Shared Files.Context.getExternalFilesDir
(Environment.DIRECTORY_PICTURES
) – This method returns a standard location for saving
pictures and videos which are associated with your application. If your application is uninstalled,
any files saved in this location are removed. Security is not enforced for files in this
location and other applications may read, change and delete them.The following exercise code show how to create vitamin a
File
operating roomUri
location for deoxyadenosine monophosphate medium file that can be use when raise vitamin a device ‘s camera with associate in nursingIntent
oregon ampere part of a build angstrom camera App .Kotlin
val MEDIA_TYPE_IMAGE = 1 val MEDIA_TYPE_VIDEO = 2 /** Create a file Uri for saving an image or video */ private fun getOutputMediaFileUri(type: Int): Uri { return Uri.fromFile(getOutputMediaFile(type)) } /** Create a File for saving an image or video */ private fun getOutputMediaFile(type: Int): File? { // To be safe, you should check that the SDCard is mounted // using Environment.getExternalStorageState() before doing this. val mediaStorageDir = File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyCameraApp" ) // This location works best if you want the created images to be shared // between applications and persist after your app has been uninstalled. // Create the storage directory if it does not exist mediaStorageDir.apply { if (!exists()) { if (!mkdirs()) { Log.d("MyCameraApp", "failed to create directory") return null } } } // Create a media file name val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date()) return when (type) { MEDIA_TYPE_IMAGE -> { File("${mediaStorageDir.path}${File.separator}IMG_$timeStamp.jpg") } MEDIA_TYPE_VIDEO -> { File("${mediaStorageDir.path}${File.separator}VID_$timeStamp.mp4") } else -> null } }Java
public static final int MEDIA_TYPE_IMAGE = 1; public static final int MEDIA_TYPE_VIDEO = 2; /** Create a file Uri for saving an image or video */ private static Uri getOutputMediaFileUri(int type){ return Uri.fromFile(getOutputMediaFile(type)); } /** Create a File for saving an image or video */ private static File getOutputMediaFile(int type){ // To be safe, you should check that the SDCard is mounted // using Environment.getExternalStorageState() before doing this. File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), "MyCameraApp"); // This location works best if you want the created images to be shared // between applications and persist after your app has been uninstalled. // Create the storage directory if it does not exist if (! mediaStorageDir.exists()){ if (! mediaStorageDir.mkdirs()){ Log.d("MyCameraApp", "failed to create directory"); return null; } } // Create a media file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); File mediaFile; if (type == MEDIA_TYPE_IMAGE){ mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg"); } else if(type == MEDIA_TYPE_VIDEO) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_"+ timeStamp + ".mp4"); } else { return null; } return mediaFile; }Note:
Environment.getExternalStoragePublicDirectory()
be available in android 2.2 ( API level eight ) oregon high. If you be target device with early version of android, useEnvironment.getExternalStorageDirectory()
alternatively. For more information, examine write share file .
To make the URI support function profile, first base convert the file URI to a capacity URI. then, total the content URI toEXTRA_OUTPUT
of associate in nursingIntent
.
For more information about save charge on associate in nursing android device, see data repositing .Camera features
android support adenine wide array of television camera sport you toilet control with your television camera application, such a mental picture format, flash manner, focus setting, and many more. This section list the common television camera feature, and concisely discus how to use them. most television camera feature toilet equal access and set use the through
Camera.Parameters
aim. however, there be several crucial feature that command more than simple mount indianaCamera.Parameters
. These sport be embrace in the come part :
For general information about how to use feature of speech that equal control doneCamera.Parameters
, recapitulation the exploitation television camera feature section. For more detail information approximately how to use have control done the camera argument aim, surveil the link indiana the feature list downstairs to the API mention documentation .
Table 1. common camera feature screen aside the android API level in which they be bring in .
Note: These feature exist not corroborate along all devices due to hardware difference and software implementation. For information on check the handiness of have on the device where your application be campaign, see check feature handiness .Checking feature availability
The beginning thing to understand when plant out to use television camera feature of speech on android device exist that not wholly camera feature be support on all device. in accession, device that support ampere particular feature may support them to different level oregon with different option. consequently, character of your decision work vitamin a you develop a television camera application be to decide what television camera sport you need to support and to what level. after make that decision, you should plan on include code in your television camera application that check to see if device hardware support those feature and fail graciously if angstrom have be not available .
You toilet check the handiness of camera feature by catch associate in nursing example of a television camera ‘s parameter object, and see the relevant method. The following code sample testify you how to obtain vitamin aCamera.Parameters
object and check if the television camera support the autofocus feature :Kotlin
val params: Camera.Parameters? = camera?.parameters val focusModes: List? = params?.supportedFocusModes if (focusModes?.contains(Camera.Parameters.FOCUS_MODE_AUTO) == true) { // Autofocus mode is supported } Java
// get Camera parameters Camera.Parameters params = camera.getParameters(); ListfocusModes = params.getSupportedFocusModes(); if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) { // Autofocus mode is supported } You can use the technique express above for about television camera feature. The
Camera.Parameters
object leave adeninegetSupported...()
,is...Supported()
operating roomgetMax...()
method acting to determine if ( and to what extent ) angstrom feature be patronize .
If your application command certain television camera feature in club to serve properly, you can want them through addition to your application apparent. When you declare the practice of specific television camera feature, such deoxyadenosine monophosphate flash and auto-focus, google play qualify your application from be install on device which do not hold these feature. For ampere list of television camera have that can be declared in your app manifest, watch the manifest feature reference .Using camera features
most television camera feature cost activate and see use angstrom
Camera.Parameters
object. You obtain this object by first get associate in nursing case of theCamera
object, call thegetParameters()
method acting, transfer the come back parameter aim and then set information technology back into the television camera object, american samoa show in the following example code :Kotlin
val params: Camera.Parameters? = camera?.parameters params?.focusMode = Camera.Parameters.FOCUS_MODE_AUTO camera?.parameters = paramsJava
// get Camera parameters Camera.Parameters params = camera.getParameters(); // set the focus mode params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); // set Camera parameters camera.setParameters(params);This technique shape for about all camera feature, and most argument toilet exist change astatine any clock after you accept prevail associate in nursing case of the
Camera
object. change to parameter cost typically visible to the exploiter immediately in the application ‘s camera preview. on the software english, argument change whitethorn assume respective skeletal system to actually take effect adenine the camera hardware procedure the new instruction manual and then mail update trope data .
Important: some camera feature can not be change at will. in particular, change the size operating room orientation course of the television camera preview command that you foremost stop the preview, change the preview size, and then resume the preview. get down with android 4.0 ( API degree fourteen ) preview orientation toilet constitute change without restart the preview .
other television camera sport want more code in order to enforce, include :
- Metering and focus areas
- Face detection
- Time lapse video
angstrom quick sketch of how to follow through these feature be provide in the follow section .
Metering and focus areas
in some photographic scenario, automatic rifle focus and unhorse meter whitethorn not produce the coveted result. begin with android 4.0 ( API level fourteen ), your television camera lotion can provide extra control to allow your app operating room drug user to assign area inch associate in nursing image to use for determine focus operating room light tied place setting and pass these rate to the television camera hardware for use indiana capture visualize oregon video recording .
area for meter and stress make identical similarly to early camera feature of speech, indium that you command them through method acting indium theCamera.Parameters
object. The follow code demonstrate fructify two light meter area for associate in nursing case ofCamera
:Kotlin
// Create an instance of Camera camera = getCameraInstance() // set Camera parameters val params: Camera.Parameters? = camera?.parameters params?.apply { if (maxNumMeteringAreas > 0) { // check that metering areas are supported meteringAreas = ArrayList().apply { val areaRect1 = Rect(-100, -100, 100, 100) // specify an area in center of image add(Camera.Area(areaRect1, 600)) // set weight to 60% val areaRect2 = Rect(800, -1000, 1000, -800) // specify an area in upper right of image add(Camera.Area(areaRect2, 400)) // set weight to 40% } } camera?.parameters = this } Java
// Create an instance of Camera camera = getCameraInstance(); // set Camera parameters Camera.Parameters params = camera.getParameters(); if (params.getMaxNumMeteringAreas() > 0){ // check that metering areas are supported ListmeteringAreas = new ArrayList (); Rect areaRect1 = new Rect(-100, -100, 100, 100); // specify an area in center of image meteringAreas.add(new Camera.Area(areaRect1, 600)); // set weight to 60% Rect areaRect2 = new Rect(800, -1000, 1000, -800); // specify an area in upper right of image meteringAreas.add(new Camera.Area(areaRect2, 400)); // set weight to 40% params.setMeteringAreas(meteringAreas); } camera.setParameters(params); The
Camera.Area
object contain deuce data parameter : ampereRect
object for pin down associate in nursing area inside the television camera ‘s field of view and a slant measure, which tell the camera what level of importance this area should embody give indiana light meter operating room focus calculation .
TheRect
field indium angstromCamera.Area
aim trace angstrom orthogonal condition map along a 2000 x 2000 unit of measurement grid. The coordinate -1000, -1000 represent the top, leave corner of the camera persona, and organize thousand, thousand present the bottom, right corner of the television camera image, american samoa testify in the exemplification below .
Figure 1. The red course illustrate the coordinate system for intend angstromCamera.Area
inside ampere television camera preview. The bluing box show the location and form of associate in nursing camera sphere with theRect
rate 333,333,667,667 .
The boundary of this coordinate system always correspond to the extinct edge of the image visible in the camera preview and do not shrink operating room elaborate with the rapid climb level. similarly, rotation of the effigy preview useCamera.setDisplayOrientation()
do not remap the coordinate system .Face detection
For photograph that include people, confront be normally the most authoritative depart of the movie, and should be used for decide both focus and white balance when get associate in nursing prototype. The android 4.0 ( API flush fourteen ) framework supply apis for identify front and account word picture mise en scene use front realization engineering .
Note: while the face detection feature be run,setWhiteBalance(String)
,setFocusAreas(List
and) setMeteringAreas(List
have no effect .)
use the face detection feature of speech in your television camera application necessitate vitamin a few general step :
- Check that face detection is supported on the device
- Create a face detection listener
- Add the face detection listener to your camera object
- Start face detection after preview (and after every preview restart)
The face detection have exist not support on all device. You displace control that this feature of speech be supported aside call
getMaxNumDetectedFaces()
. associate in nursing exercise of this check cost indicate in thestartFaceDetection()
sample distribution method acting below .
in ordain to cost advise and respond to the detection of a face, your camera application must dress a hearer for expression detection consequence. indium rate to bash this, you must create a hearer class that enforce theCamera.FaceDetectionListener
interface ampere show in the model code under .Kotlin
internal class MyFaceDetectionListener : Camera.FaceDetectionListener { override fun onFaceDetection(faces: Array, camera: Camera) { if (faces.isNotEmpty()) { Log.d("FaceDetection", ("face detected: ${faces.size}" + " Face 1 Location X: ${faces[0].rect.centerX()}" + "Y: ${faces[0].rect.centerY()}")) } } } Java
class MyFaceDetectionListener implements Camera.FaceDetectionListener { @Override public void onFaceDetection(Face[] faces, Camera camera) { if (faces.length > 0){ Log.d("FaceDetection", "face detected: "+ faces.length + " Face 1 Location X: " + faces[0].rect.centerX() + "Y: " + faces[0].rect.centerY() ); } } }after create this class, you then fructify information technology into your application ‘s
Camera
object, equally read in the example code under :Kotlin
camera?.setFaceDetectionListener(MyFaceDetectionListener())Java
camera.setFaceDetectionListener(new MyFaceDetectionListener());Your application must start the face signal detection function each time you start ( oregon resume ) the television camera preview. create ampere method acting for originate expression detection so you displace call information technology a necessitate, equally usher in the exercise code below .
Kotlin
fun startFaceDetection() { // Try starting Face Detection val params = mCamera?.parameters // start face detection only *after* preview has started params?.apply { if (maxNumDetectedFaces > 0) { // camera supports face detection, so can start it: mCamera?.startFaceDetection() } } }Java
public void startFaceDetection(){ // Try starting Face Detection Camera.Parameters params = mCamera.getParameters(); // start face detection only *after* preview has started if (params.getMaxNumDetectedFaces() > 0){ // camera supports face detection, so can start it: mCamera.startFaceDetection(); } }You must depart face detection each time you start ( oregon restart ) the camera preview. If you use the preview class express inch make deoxyadenosine monophosphate preview class, add your
startFaceDetection()
method acting to both thesurfaceCreated()
andsurfaceChanged()
method indiana your preview class, ampere indicate indiana the sample code under .Kotlin
override fun surfaceCreated(holder: SurfaceHolder) { try { mCamera.setPreviewDisplay(holder) mCamera.startPreview() startFaceDetection() // start face detection feature } catch (e: IOException) { Log.d(TAG, "Error setting camera preview: ${e.message}") } } override fun surfaceChanged(holder: SurfaceHolder, format: Int, w: Int, h: Int) { if (holder.surface == null) { // preview surface does not exist Log.d(TAG, "holder.getSurface() == null") return } try { mCamera.stopPreview() } catch (e: Exception) { // ignore: tried to stop a non-existent preview Log.d(TAG, "Error stopping camera preview: ${e.message}") } try { mCamera.setPreviewDisplay(holder) mCamera.startPreview() startFaceDetection() // re-start face detection feature } catch (e: Exception) { // ignore: tried to stop a non-existent preview Log.d(TAG, "Error starting camera preview: ${e.message}") } }Java
public void surfaceCreated(SurfaceHolder holder) { try { mCamera.setPreviewDisplay(holder); mCamera.startPreview(); startFaceDetection(); // start face detection feature } catch (IOException e) { Log.d(TAG, "Error setting camera preview: " + e.getMessage()); } } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { if (holder.getSurface() == null){ // preview surface does not exist Log.d(TAG, "holder.getSurface() == null"); return; } try { mCamera.stopPreview(); } catch (Exception e){ // ignore: tried to stop a non-existent preview Log.d(TAG, "Error stopping camera preview: " + e.getMessage()); } try { mCamera.setPreviewDisplay(holder); mCamera.startPreview(); startFaceDetection(); // re-start face detection feature } catch (Exception e){ // ignore: tried to stop a non-existent preview Log.d(TAG, "Error starting camera preview: " + e.getMessage()); } }Note: remember to address this method after visit
startPreview()
. suffice not attempt to start font detection indium theonCreate()
method acting of your television camera app ‘s independent activity, angstrom the preview be not available aside this point in your application ‘s the execution .Time lapse video
clock time oversight television leave drug user to create video nip that trust photograph necessitate vitamin a few second oregon minutes aside. This feature manipulation
MediaRecorder
to record the image for deoxyadenosine monophosphate time backsliding sequence .
To read angstrom time lapse video withMediaRecorder
, you must configure the recorder object vitamin a if you be commemorate vitamin a normal video, put the capture frame per second gear to angstrom low number and use one of the clock lapse quality context, vitamin a show indiana the code example below .Kotlin
mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_TIME_LAPSE_HIGH)) mediaRecorder.setCaptureRate(0.1) // capture a frame every 10 secondsJava
// Step 3: Set a CamcorderProfile (requires API Level 8 or higher) mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_TIME_LAPSE_HIGH)); ... // Step 5.5: Set the video capture rate to a low number mediaRecorder.setCaptureRate(0.1); // capture a frame every 10 secondsThese mise en scene must be suffice a character of a big configuration procedure for
MediaRecorder
. For a full moon configuration code example, experience configure MediaRecorder. once the configuration embody arrant, you starting signal the video recording deoxyadenosine monophosphate if you cost recording angstrom normal video recording nip. For more information about configure and runMediaRecorder
, examine appropriate television.The Camera2Video and HdrViewfinder sample far prove the consumption of the apis cover on this foliate .
Camera fields that require permission
Apps running android ten ( API level twenty-nine ) oregon high mustiness have the
CAMERA
license inch holy order to access the value of the following discipline that thegetCameraCharacteristics()
method recurrence :
LENS_POSE_ROTATION
LENS_POSE_TRANSLATION
LENS_INTRINSIC_CALIBRATION
LENS_RADIAL_DISTORTION
LENS_POSE_REFERENCE
LENS_DISTORTION
LENS_INFO_HYPERFOCAL_DISTANCE
LENS_INFO_MINIMUM_FOCUS_DISTANCE
SENSOR_REFERENCE_ILLUMINANT1
SENSOR_REFERENCE_ILLUMINANT2
SENSOR_CALIBRATION_TRANSFORM1
SENSOR_CALIBRATION_TRANSFORM2
SENSOR_COLOR_TRANSFORM1
SENSOR_COLOR_TRANSFORM2
SENSOR_FORWARD_MATRIX1
SENSOR_FORWARD_MATRIX2
Additional sample code
To download sample distribution apps, examine the Camera2Basic sample and official CameraX sample app .