banner



Do I Need Camera Permission For Take A Picture Android

The Android framework includes support for diverse cameras and camera features bachelor on devices, allowing you to capture pictures and videos in your applications. This document discusses a quick, simple arroyo to image and video capture and outlines an advanced arroyo for creating custom camera experiences for your users.

Note: This folio describes the Camera course, which has been deprecated. We recommend using the CameraX Jetpack library or, for specific use cases, the camera2, form. Both CameraX and Camera2 work on Android 5.0 (API level 21) and higher.

Considerations

Before enabling your application to utilize cameras on Android devices, you lot should consider a few questions about how your app intends to utilise this hardware feature.

  • Camera Requirement - Is the use of a camera so important to your awarding that you do not desire your application installed on a device that does non 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 simply interested in snapping a quick picture or video clip, or will your awarding provide a new manner to employ cameras? For getting a quick snap or clip, consider Using Existing Camera Apps. For developing a customized camera characteristic, check out the Building a Camera App section.
  • Foreground Services Requirement - When does your app collaborate with the camera? On Android ix (API level 28) and later, apps running in the background cannot access the camera. Therefore, you should employ the camera either when your app is in the foreground or equally part of a foreground service.
  • Storage - Are the images or videos your application generates intended to be only visible to your awarding or shared so that other applications such as Gallery or other media and social apps can use them? Do yous want the pictures and videos to be available even if your application is uninstalled? Check out the Saving Media Files section to meet how to implement these options.

The basics

The Android framework supports capturing images and video through the android.hardware.camera2 API or camera Intent. Here are the relevant classes:

android.hardware.camera2
This parcel is the principal API for decision-making device cameras. It tin 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 photographic camera preview to the user.
MediaRecorder
This course is used to record video from the photographic camera.
Intent
An intent activity type of MediaStore.ACTION_IMAGE_CAPTURE or MediaStore.ACTION_VIDEO_CAPTURE tin be used to capture images or videos without directly using the Camera object.

Manifest declarations

Before starting development on your application with the Camera API, you should brand sure your manifest has the advisable declarations to permit use of camera hardware and other related features.

  • Camera Permission - Your application must asking permission to use a device photographic camera.
    <uses-permission android:name="android.permission.Camera" />            

    Annotation: If y'all are using the camera by invoking an existing photographic camera app, your application does non need to request this permission.

  • Camera Features - Your awarding must also declare use of camera features, for case:
    <uses-feature android:proper noun="android.hardware.photographic camera" />            

    For a list of camera features, come across the manifest Features Reference.

    Calculation camera features to your manifest causes Google Play to forbid your application from being installed to devices that do not include a camera or practise not support the photographic camera features you specify. For more data about using feature-based filtering with Google Play, meet Google Play and Feature-Based Filtering.

    If your awarding tin can apply a camera or camera feature for proper operation, but does not require it, you should specify this in the manifest by including the android:required aspect, and setting information technology to false:

    <uses-feature android:name="android.hardware.camera" android:required="imitation" />            
  • Storage Permission - Your application can save images or videos to the device'south external storage (SD Card) if it targets Android 10 (API level 29) or lower and specifies the following in the manifest.
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />            
  • Audio Recording Permission - For recording audio with video capture, your application must asking the audio capture permission.
    <uses-permission android:name="android.permission.RECORD_AUDIO" />            
  • Location Permission - If your application tags images with GPS location information, you must asking the ACCESS_FINE_LOCATION permission. Note that, if your app targets Android 5.0 (API level 21) or college, you likewise need to declare that your app uses the device'due south GPS:

    <uses-permission android:proper name="android.permission.ACCESS_FINE_LOCATION" /> ... <!-- Needed but if your app targets Android 5.0 (API level 21) or college. --> <uses-feature android:name="android.hardware.location.gps" />            

    For more than information well-nigh getting user location, see Location Strategies.

Using existing camera apps

A quick way to enable taking pictures or videos in your awarding without a lot of extra code is to use an Intent to invoke an existing Android camera awarding. The details are described in the training lessons Taking Photos Merely and Recording Videos Merely.

Edifice a camera app

Some developers may require a camera user interface that is customized to the expect of their awarding or provides special features. Writing your own picture show-taking code tin provide a more than compelling feel for your users.

Note: The following guide is for the older, deprecated Camera API. For new or advanced camera applications, the newer android.hardware.camera2 API is recommended.

The general steps for creating a custom camera interface for your application are every bit follows:

  • Detect and Access Camera - Create code to check for the existence of cameras and request access.
  • Create a Preview Class - Create a photographic camera preview class that extends SurfaceView and implements the SurfaceHolder interface. This class previews the live images from the camera.
  • Build a Preview Layout - Once you lot have the camera preview class, create a view layout that incorporates the preview and the user interface controls you lot want.
  • Setup Listeners for Capture - Connect listeners for your interface controls to kickoff epitome 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 Photographic camera - After using the camera, your awarding must properly release information technology for use past other applications.

Camera hardware is a shared resources that must be carefully managed so your application does not collide with other applications that may too want to utilize it. The following sections discusses how to detect photographic camera hardware, how to request admission to a camera, how to capture pictures or video and how to release the photographic camera when your application is done using it.

Caution: Remember to release the Camera object by calling the Camera.release() when your awarding is washed using it! If your awarding does not properly release the camera, all subsequent attempts to access the camera, including those by your own application, will fail and may cause your or other applications to be close downwardly.

Detecting camera hardware

If your application does not specifically require a photographic camera using a manifest declaration, you should bank check to come across if a camera is bachelor at runtime. To perform this check, utilize the PackageManager.hasSystemFeature() method, equally shown in the example lawmaking below:

Kotlin

/** Bank check if this device has a photographic camera */ individual fun checkCameraHardware(context: Context): Boolean {     if (context.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {         // this device has a photographic camera         render truthful     } else {         // no camera on this device         render 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         render false;     } }            

Android devices can have multiple cameras, for example a back-facing camera for photography and a front end-facing camera for video calls. Android 2.three (API Level 9) and later on allows yous to check the number of cameras available on a device using the Camera.getNumberOfCameras() method.

Accessing cameras

If you have adamant that the device on which your application is running has a photographic camera, you must asking to access it past getting an instance of Camera (unless you are using an intent to access the camera).

To access the primary photographic camera, use the Photographic camera.open() method and exist sure to catch whatever exceptions, every bit shown in the code below:

Kotlin

/** A safe way to become an instance of the Camera object. */ fun getCameraInstance(): Photographic camera? {     return try {         Camera.open up() // attempt to become a Photographic camera case     } catch (eastward: Exception) {         // Camera is non bachelor (in utilize or does not be)         null // returns null if camera is unavailable     } }            

Java

/** A condom way to become an instance of the Photographic camera object. */ public static Photographic camera getCameraInstance(){     Camera c = null;     try {         c = Photographic camera.open up(); // attempt to go a Camera instance     }     catch (Exception eastward){         // Camera is not available (in use or does not exist)     }     render c; // returns null if photographic camera is unavailable }            

Caution: Always cheque for exceptions when using Camera.open up(). Failing to check for exceptions if the camera is in use or does non exist volition cause your application to exist shut down by the system.

On devices running Android two.3 (API Level 9) or higher, you lot tin can access specific cameras using Camera.open(int). The instance code higher up volition admission the first, back-facing photographic camera on a device with more than i camera.

Checking camera features

Once you obtain access to a camera, y'all can get further information well-nigh its capabilities using the Camera.getParameters() method and checking the returned Photographic camera.Parameters object for supported capabilities. When using API Level 9 or higher, use the Camera.getCameraInfo() to determine if a camera is on the front or back of the device, and the orientation of the image.

Creating a preview form

For users to effectively take pictures or video, they must be able to see what the device photographic camera sees. A camera preview class is a SurfaceView that can display the alive image data coming from a photographic camera, and so users tin frame and capture a picture or video.

The following example lawmaking demonstrates how to create a basic camera preview course that can exist included in a View layout. This class implements SurfaceHolder.Callback in order to capture the callback events for creating and destroying the view, which are needed for assigning the camera preview input.

Kotlin

/** A basic Photographic camera preview grade */ class CameraPreview(         context: Context,         private val mCamera: Photographic camera ) : SurfaceView(context), SurfaceHolder.Callback {      private val mHolder: SurfaceHolder = holder.apply {         // Install a SurfaceHolder.Callback so we go notified when the         // underlying surface is created and destroyed.         addCallback(this@CameraPreview)         // deprecated setting, just required on Android versions prior to 3.0         setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS)     }      override fun surfaceCreated(holder: SurfaceHolder) {         // The Surface has been created, at present tell the photographic camera where to draw the preview.         mCamera.apply {             try {                 setPreviewDisplay(holder)                 startPreview()             } grab (e: IOException) {                 Log.d(TAG, "Mistake 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, westward: Int, h: Int) {         // If your preview can change or rotate, take care of those events here.         // Brand sure to stop the preview before resizing or reformatting it.         if (mHolder.surface == null) {             // preview surface does not be             render         }          // terminate preview before making changes         try {             mCamera.stopPreview()         } grab (east: Exception) {             // ignore: tried to stop a non-existent preview         }          // set preview size and make whatsoever resize, rotate or         // reformatting changes hither          // outset preview with new settings         mCamera.utilize {             try {                 setPreviewDisplay(mHolder)                 startPreview()             } catch (e: Exception) {                 Log.d(TAG, "Error starting camera preview: ${due east.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 iii.0         mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);     }      public void surfaceCreated(SurfaceHolder holder) {         // The Surface has been created, now tell the photographic camera where to draw the preview.         effort {             mCamera.setPreviewDisplay(holder);             mCamera.startPreview();         } catch (IOException eastward) {             Log.d(TAG, "Error setting camera preview: " + e.getMessage());         }     }      public void surfaceDestroyed(SurfaceHolder holder) {         // empty. Take care of releasing the Photographic 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 information technology.          if (mHolder.getSurface() == zero){           // preview surface does not be           return;         }          // stop preview before making changes         try {             mCamera.stopPreview();         } grab (Exception eastward){           // ignore: tried to stop a non-existent preview         }          // set preview size and brand any resize, rotate or         // reformatting changes hither          // start preview with new settings         try {             mCamera.setPreviewDisplay(mHolder);             mCamera.startPreview();          } grab (Exception e){             Log.d(TAG, "Error starting camera preview: " + e.getMessage());         }     } }            

If you want to set a specific size for your photographic camera preview, prepare this in the surfaceChanged() method equally noted in the comments in a higher place. When setting preview size, yous must use values from getSupportedPreviewSizes(). Exercise non set arbitrary values in the setPreviewSize() method.

Notation: With the introduction of the Multi-Window feature in Android seven.0 (API level 24) and higher, you can no longer assume the attribute ratio of the preview is the same as your action fifty-fifty after calling setDisplayOrientation(). Depending on the window size and aspect ratio, you may may have to fit a wide camera preview into a portrait-orientated layout, or vice versa, using a letterbox layout.

Placing preview in a layout

A photographic camera preview class, such equally the instance shown in the previous section, must be placed in the layout of an activity along with other user interface controls for taking a pic or video. This section shows you how to build a basic layout and activity for the preview.

The post-obit layout code provides a very basic view that tin exist used to display a photographic camera preview. In this example, the FrameLayout chemical element is meant to be the container for the camera preview class. This layout type is used then that additional picture information or controls can be overlaid on the live camera preview images.

<?xml version="1.0" encoding="utf-viii"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:orientation="horizontal"     android:layout_width="fill_parent"     android:layout_height="fill_parent"     >   <FrameLayout     android:id="@+id/camera_preview"     android:layout_width="fill_parent"     android:layout_height="fill_parent"     android:layout_weight="1"     />    <Button     android:id="@+id/button_capture"     android:text="Capture"     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:layout_gravity="center"     /> </LinearLayout>        

On most devices, the default orientation of the camera preview is landscape. This example layout specifies a horizontal (landscape) layout and the code below fixes the orientation of the application to landscape. For simplicity in rendering a photographic camera preview, you should alter your application's preview activity orientation to mural by adding the following to your manifest.

<activity android:proper name=".CameraActivity"           android:label="@string/app_name"            android:screenOrientation="mural">           <!-- configure this activity to use mural orientation -->            <intent-filter>         <action android:name="android.intent.action.Primary" />         <category android:proper noun="android.intent.category.LAUNCHER" />     </intent-filter> </action>        

Annotation: A camera preview does non accept to exist in mural style. Starting in Android two.2 (API Level 8), you lot can use the setDisplayOrientation() method to gear up the rotation of the preview image. In guild to change preview orientation as the user re-orients the phone, within the surfaceChanged() method of your preview form, first stop the preview with Camera.stopPreview() change the orientation and and so start the preview again with Camera.startPreview().

In the action for your camera view, add your preview grade to the FrameLayout element shown in the example to a higher place. Your photographic camera activity must likewise ensure that information technology releases the camera when it is paused or close down. The post-obit example shows how to modify a camera action to attach the preview class shown in Creating a preview form.

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, information technology)         }          // Set the Preview view as the content of our activity.         mPreview?.also {             val preview: FrameLayout = findViewById(R.id.camera_preview)             preview.addView(it)         }     } }            

Coffee

public course CameraActivity extends Activity {      individual Camera mCamera;     individual CameraPreview mPreview;      @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.main);          // Create an case of Photographic camera         mCamera = getCameraInstance();          // Create our Preview view and set information technology 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 example above refers to the instance method shown in Accessing cameras.

Capturing pictures

Once y'all have congenital a preview class and a view layout in which to display it, you are fix to start capturing images with your application. In your application lawmaking, you must fix listeners for your user interface controls to reply to a user action by taking a picture.

In order to recollect a picture, use the Camera.takePicture() method. This method takes three parameters which receive data from the camera. In order to receive data in a JPEG format, you lot must implement an Camera.PictureCallback interface to receive the image data and write it to a file. The following code shows a basic implementation of the Camera.PictureCallback interface to save an image received from the camera.

Kotlin

private val mPicture = Camera.PictureCallback { information, _ ->     val pictureFile: File = getOutputMediaFile(MEDIA_TYPE_IMAGE) ?: run {         Log.d(TAG, ("Mistake creating media file, check storage permissions"))         return@PictureCallback     }      effort {         val fos = FileOutputStream(pictureFile)         fos.write(information)         fos.close()     } catch (e: FileNotFoundException) {         Log.d(TAG, "File non found: ${e.message}")     } catch (e: IOException) {         Log.d(TAG, "Mistake accessing file: ${e.message}")     } }            

Coffee

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");             render;         }          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());         }     } };            

Trigger capturing an paradigm by calling the Camera.takePicture() method. The following example code shows how to telephone call this method from a push View.OnClickListener.

Kotlin

val captureButton: Push button = findViewById(R.id.button_capture) captureButton.setOnClickListener {     // get an image from the photographic 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(cypher, cipher, picture);         }     } );            

Note: The mPicture member in the following example refers to the case lawmaking in a higher place.

Caution: Call back to release the Camera object by calling the Camera.release() when your awarding is done using it! For information nearly how to release the camera, see Releasing the camera.

Capturing videos

Video capture using the Android framework requires careful management of the Camera object and coordination with the MediaRecorder class. When recording video with Camera, you must manage the Photographic camera.lock() and Camera.unlock() calls to allow MediaRecorder access to the camera hardware, in add-on to the Camera.open() and Photographic camera.release() calls.

Note: Starting with Android four.0 (API level 14), the Photographic camera.lock() and Camera.unlock() calls are managed for you automatically.

Unlike taking pictures with a device camera, capturing video requires a very item call order. Yous must follow a specific order of execution to successfully prepare for and capture video with your application, as detailed below.

  1. Open up Camera - Use the Camera.open() to get an instance of the camera object.
  2. Connect Preview - Prepare a live photographic camera image preview by connecting a SurfaceView to the camera using Camera.setPreviewDisplay().
  3. Start Preview - Call Camera.startPreview() to begin displaying the live camera images.
  4. Start Recording Video - The following steps must exist completed in order to successfully record video:
    1. Unlock the Photographic camera - Unlock the camera for utilize by MediaRecorder by calling Camera.unlock().
    2. Configure MediaRecorder - Telephone call in the following MediaRecorder methods in this order. For more information, come across the MediaRecorder reference documentation.
      1. setCamera() - Set the photographic camera to exist used for video capture, use your awarding's current instance of Camera.
      2. setAudioSource() - Set the sound source, use MediaRecorder.AudioSource.CAMCORDER.
      3. setVideoSource() - Set up the video source, use MediaRecorder.VideoSource.Photographic camera.
      4. Ready the video output format and encoding. For Android 2.two (API Level 8) and college, employ the MediaRecorder.setProfile method, and become a contour instance using CamcorderProfile.get(). For versions of Android prior to two.two, you must set the video output format and encoding parameters:
        1. setOutputFormat() - Gear up the output format, specify the default setting or MediaRecorder.OutputFormat.MPEG_4.
        2. setAudioEncoder() - Set the sound encoding type, specify the default setting or MediaRecorder.AudioEncoder.AMR_NB.
        3. setVideoEncoder() - Set the video encoding blazon, specify the default setting or MediaRecorder.VideoEncoder.MPEG_4_SP.
      5. setOutputFile() - Ready the output file, use getOutputMediaFile(MEDIA_TYPE_VIDEO).toString() from the case method in the Saving Media Files department.
      6. setPreviewDisplay() - Specify the SurfaceView preview layout element for your application. Use the same object y'all specified for Connect Preview.

      Caution: You must call these MediaRecorder configuration methods in this society, otherwise your application volition encounter errors and the recording will fail.

    3. Prepare MediaRecorder - Prepare the MediaRecorder with provided configuration settings by calling MediaRecorder.prepare().
    4. Starting time MediaRecorder - First recording video by calling MediaRecorder.start().
  5. Terminate Recording Video - Call the following methods in order, to successfully complete a video recording:
    1. Stop MediaRecorder - Stop recording video by calling MediaRecorder.stop().
    2. Reset MediaRecorder - Optionally, remove the configuration settings from the recorder by calling MediaRecorder.reset().
    3. Release MediaRecorder - Release the MediaRecorder by calling MediaRecorder.release().
    4. Lock the Photographic camera - Lock the camera then that time to come MediaRecorder sessions can utilise it by calling Photographic camera.lock(). Starting with Android 4.0 (API level fourteen), this call is not required unless the MediaRecorder.ready() call fails.
  6. Stop the Preview - When your activity has finished using the photographic camera, stop the preview using Camera.stopPreview().
  7. Release Photographic camera - Release the camera so that other applications can use information technology by calling Camera.release().

Note: Information technology is possible to utilise MediaRecorder without creating a camera preview first and skip the first few steps of this process. However, since users typically prefer to run into a preview before starting a recording, that process is non discussed hither.

Tip: If your awarding is typically used for recording video, prepare setRecordingHint(boolean) to true prior to starting your preview. This setting can help reduce the fourth dimension it takes to start recording.

Configuring MediaRecorder

When using the MediaRecorder class to record video, you lot must perform configuration steps in a specific social club and so telephone call the MediaRecorder.prepare() method to bank check and implement the configuration. The post-obit example code demonstrates how to properly configure and prepare the MediaRecorder class for video recording.

Kotlin

private fun prepareVideoRecorder(): Boolean {     mediaRecorder = MediaRecorder()      mCamera?.let { camera ->         // Step ane: Unlock and prepare photographic camera to MediaRecorder         camera?.unlock()          mediaRecorder?.run {             setCamera(camera)              // Step 2: Set sources             setAudioSource(MediaRecorder.AudioSource.CAMCORDER)             setVideoSource(MediaRecorder.VideoSource.CAMERA)              // Step three: Fix 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: Fix the preview output             setPreviewDisplay(mPreview?.holder?.surface)              setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)             setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT)             setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT)               // Footstep 6: Fix configured MediaRecorder             return try {                 prepare()                 true             } catch (e: IllegalStateException) {                 Log.d(TAG, "IllegalStateException preparing MediaRecorder: ${e.message}")                 releaseMediaRecorder()                 simulated             } catch (e: IOException) {                 Log.d(TAG, "IOException preparing MediaRecorder: ${e.message}")                 releaseMediaRecorder()                 false             }         }      }     return false }            

Coffee

private boolean prepareVideoRecorder(){      mCamera = getCameraInstance();     mediaRecorder = new MediaRecorder();      // Stride ane: Unlock and prepare camera to MediaRecorder     mCamera.unlock();     mediaRecorder.setCamera(mCamera);      // Footstep 2: Set sources     mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);     mediaRecorder.setVideoSource(MediaRecorder.VideoSource.Camera);      // Step three: Fix a CamcorderProfile (requires API Level viii or college)     mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));      // Stride four: Set output file     mediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString());      // Step five: Prepare 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: " + eastward.getMessage());         releaseMediaRecorder();         return faux;     } catch (IOException e) {         Log.d(TAG, "IOException preparing MediaRecorder: " + eastward.getMessage());         releaseMediaRecorder();         render false;     }     return true; }            

Prior to Android 2.2 (API Level viii), you must prepare the output format and encoding formats parameters directly, instead of using CamcorderProfile. This approach is demonstrated in the post-obit code:

Kotlin

              // Step three: Set output format and encoding (for versions prior to API Level 8)     mediaRecorder?.utilize {         setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)         setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT)         setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT)     }            

Coffee

              // Pace 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 post-obit video recording parameters for MediaRecorder are given default settings, even so, y'all may want to accommodate these settings for your application:

  • setVideoEncodingBitRate()
  • setVideoSize()
  • setVideoFrameRate()
  • setAudioEncodingBitRate()
  • setAudioChannels()
  • setAudioSamplingRate()

Starting and stopping MediaRecorder

When starting and stopping video recording using the MediaRecorder class, you must follow a specific order, equally listed below.

  1. Unlock the camera with Camera.unlock()
  2. Configure MediaRecorder as shown in the code example to a higher place
  3. Starting time recording using MediaRecorder.start()
  4. Record the video
  5. Stop recording using MediaRecorder.stop()
  6. Release the media recorder with MediaRecorder.release()
  7. Lock the camera using Camera.lock()

The post-obit case code demonstrates how to wire up a button to properly beginning and stop video recording using the camera and the MediaRecorder class.

Note: When completing a video recording, exercise non release the camera or else your preview volition exist stopped.

Kotlin

var isRecording = false val captureButton: Push = findViewById(R.id.button_capture) captureButton.setOnClickListener {     if (isRecording) {         // stop recording and release camera         mediaRecorder?.finish() // terminate the recording         releaseMediaRecorder() // release the MediaRecorder object         mCamera?.lock() // take camera admission 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 showtime 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 Push captureButton = (Button) findViewById(id.button_capture); captureButton.setOnClickListener(     new View.OnClickListener() {         @Override         public void onClick(View v) {             if (isRecording) {                 // terminate recording and release camera                 mediaRecorder.stop();  // cease the recording                 releaseMediaRecorder(); // release the MediaRecorder object                 mCamera.lock();         // accept camera access back from MediaRecorder                  // inform the user that recording has stopped                 setCaptureButtonText("Capture");                 isRecording = false;             } else {                 // initialize video photographic camera                 if (prepareVideoRecorder()) {                     // Camera is bachelor and unlocked, MediaRecorder is prepared,                     // now you can start recording                     mediaRecorder.start();                      // inform the user that recording has started                     setCaptureButtonText("Stop");                     isRecording = true;                 } else {                     // fix didn't work, release the camera                     releaseMediaRecorder();                     // inform user                 }             }         }     } );

Note: In the higher up example, the prepareVideoRecorder() method refers to the instance lawmaking shown in Configuring MediaRecorder. This method takes intendance of locking the camera, configuring and preparing the MediaRecorder instance.

Releasing the photographic camera

Cameras are a resources that is shared by applications on a device. Your application can make use of the camera after getting an instance of Camera, and you lot must be specially careful to release the camera object when your awarding stops using information technology, and equally soon as your application is paused (Action.onPause()). If your awarding does non properly release the photographic camera, all subsequent attempts to access the photographic camera, including those by your own application, will fail and may cause your or other applications to be shut downward.

To release an instance of the Camera object, use the Camera.release() method, as shown in the case code below.

Kotlin

form 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 information technology first         releaseCamera() // release the camera immediately on intermission event     }      private fun releaseMediaRecorder() {         mediaRecorder?.reset() // articulate recorder configuration         mediaRecorder?.release() // release the recorder object         mediaRecorder = null         mCamera?.lock() // lock camera for afterward use     }      private fun releaseCamera() {         mCamera?.release() // release the camera for other applications         mCamera = null     } }            

Java

public class CameraActivity extends Activeness {     private Camera mCamera;     private SurfaceView preview;     individual MediaRecorder mediaRecorder;      ...      @Override     protected void onPause() {         super.onPause();         releaseMediaRecorder();       // if you are using MediaRecorder, release it first         releaseCamera();              // release the camera immediately on intermission event     }      private void releaseMediaRecorder(){         if (mediaRecorder != null) {             mediaRecorder.reset();   // clear recorder configuration             mediaRecorder.release(); // release the recorder object             mediaRecorder = zilch;             mCamera.lock();           // lock camera for afterwards use         }     }      private void releaseCamera(){         if (mCamera != cipher){             mCamera.release();        // release the camera for other applications             mCamera = null;         }     } }            

Circumspection: If your application does non properly release the camera, all subsequent attempts to access the camera, including those past your own awarding, will neglect and may cause your or other applications to exist close down.

Media files created by users such as pictures and videos should exist saved to a device's external storage directory (SD Card) to conserve organization space and to allow users to access these files without their device. There are many possible directory locations to salve media files on a device, however in that location are but ii standard locations yous should consider every bit a developer:

  • Surroundings.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 detect, read, alter and delete files saved in this location. If your application is uninstalled by the user, media files saved to this location volition not be removed. To avoid interfering with users existing pictures and videos, yous should create a sub-directory for your application'southward media files within this directory, as shown in the code sample beneath. This method is available in Android two.two (API Level 8), for equivalent calls in earlier API versions, see Saving Shared Files.
  • Context.getExternalFilesDir(Surround.DIRECTORY_PICTURES) - This method returns a standard location for saving pictures and videos which are associated with your awarding. If your application is uninstalled, whatsoever 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 post-obit example code demonstrates how to create a File or Uri location for a media file that tin exist used when invoking a device'southward camera with an Intent or as office of a Building a Camera App.

Kotlin

val MEDIA_TYPE_IMAGE = one val MEDIA_TYPE_VIDEO = 2  /** Create a file Uri for saving an epitome 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(blazon: Int): File? {     // To be prophylactic, you should check that the SDCard is mounted     // using Environment.getExternalStorageState() before doing this.      val mediaStorageDir = File(             Surroundings.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 zip             }         }     }      // Create a media file name     val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Engagement())     render when (blazon) {         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 terminal int MEDIA_TYPE_IMAGE = 1; public static terminal 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(blazon)); }  /** Create a File for saving an image or video */ private static File getOutputMediaFile(int type){     // To exist prophylactic, you should cheque that the SDCard is mounted     // using Environment.getExternalStorageState() before doing this.      File mediaStorageDir = new File(Surround.getExternalStoragePublicDirectory(               Environment.DIRECTORY_PICTURES), "MyCameraApp");     // This location works best if yous desire the created images to be shared     // between applications and persist afterward your app has been uninstalled.      // Create the storage directory if information technology does not exist     if (! mediaStorageDir.exists()){         if (! mediaStorageDir.mkdirs()){             Log.d("MyCameraApp", "failed to create directory");             return nada;         }     }      // 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 nothing;     }      render mediaFile; }            

Note: Surround.getExternalStoragePublicDirectory() is bachelor in Android 2.ii (API Level 8) or college. If y'all are targeting devices with earlier versions of Android, use Surroundings.getExternalStorageDirectory() instead. For more than data, see Saving Shared Files.

To brand the URI back up work profiles, first convert the file URI to a content URI. Then, add the content URI to EXTRA_OUTPUT of an Intent.

For more information about saving files on an Android device, run into Information Storage.

Photographic camera features

Android supports a wide array of photographic camera features you can command with your camera application, such as motion picture format, wink fashion, focus settings, and many more. This section lists the common camera features, and briefly discusses how to employ them. Most camera features can be accessed and prepare using the through Camera.Parameters object. However, there are several important features that require more than than simple settings in Camera.Parameters. These features are covered in the following sections:

  • Metering and focus areas
  • Face detection
  • Time lapse video

For general information virtually how to apply features that are controlled through Photographic camera.Parameters, review the Using camera features department. For more than detailed data virtually how to utilise features controlled through the photographic camera parameters object, follow the links in the feature listing beneath to the API reference documentation.

Table one. Common camera features sorted by the Android API Level in which they were introduced.

Feature API Level Clarification
Face up Detection 14 Identify man faces inside a picture and use them for focus, metering and white remainder
Metering Areas 14 Specify i or more areas inside an prototype for calculating white residuum
Focus Areas 14 Set ane or more areas within an image to use for focus
White Balance Lock 14 Stop or start automatic white balance adjustments
Exposure Lock fourteen Stop or showtime automatic exposure adjustments
Video Snapshot 14 Take a picture while shooting video (frame grab)
Time Lapse Video eleven Tape frames with gear up delays to record a fourth dimension lapse video
Multiple Cameras nine Support for more than one camera on a device, including forepart-facing and back-facing cameras
Focus Distance ix Reports distances between the camera and objects that appear to be in focus
Zoom eight Set prototype magnification
Exposure Compensation 8 Increase or decrease the low-cal exposure level
GPS Information 5 Include or omit geographic location information with the paradigm
White Residuum 5 Set the white residual manner, which affects color values in the captured image
Focus Mode 5 Set how the camera focuses on a bailiwick such as automatic, stock-still, macro or infinity
Scene Mode 5 Apply a preset mode for specific types of photography situations such every bit night, embankment, snow or candlelight scenes
JPEG Quality 5 Set the compression level for a JPEG image, which increases or decreases epitome output file quality and size
Flash Style 5 Turn wink on, off, or use automatic setting
Color Effects 5 Apply a color effect to the captured image such as blackness and white, sepia tone or negative.
Anti-Banding 5 Reduces the effect of banding in color gradients due to JPEG compression
Picture Format one Specify the file format for the motion-picture show
Picture Size one Specify the pixel dimensions of the saved picture

Notation: These features are not supported on all devices due to hardware differences and software implementation. For data on checking the availability of features on the device where your application is running, see Checking characteristic availability.

Checking feature availability

The first matter to understand when setting out to use camera features on Android devices is that not all camera features are supported on all devices. In improver, devices that back up a item characteristic may support them to different levels or with different options. Therefore, part of your decision process every bit yous develop a camera awarding is to make up one's mind what camera features you want to support and to what level. Later on making that decision, you should plan on including code in your photographic camera application that checks to meet if device hardware supports those features and fails gracefully if a feature is not available.

Y'all tin can check the availability of camera features past getting an instance of a photographic camera'southward parameters object, and checking the relevant methods. The following code sample shows you how to obtain a Photographic camera.Parameters object and check if the photographic camera supports the autofocus feature:

Kotlin

val params: Camera.Parameters? = camera?.parameters val focusModes: Listing<String>? = params?.supportedFocusModes if (focusModes?.contains(Camera.Parameters.FOCUS_MODE_AUTO) == true) {     // Autofocus mode is supported }            

Java

// get Camera parameters Photographic camera.Parameters params = photographic camera.getParameters();  List<String> focusModes = params.getSupportedFocusModes(); if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {   // Autofocus mode is supported }            

You tin can apply the technique shown above for most camera features. The Camera.Parameters object provides a getSupported...(), is...Supported() or getMax...() method to determine if (and to what extent) a feature is supported.

If your awarding requires certain photographic camera features in order to role properly, you can require them through additions to your awarding manifest. When you declare the use of specific camera features, such as flash and auto-focus, Google Play restricts your application from being installed on devices which do non support these features. For a list of camera features that can be declared in your app manifest, meet the manifest Features Reference.

Using photographic camera features

About camera features are activated and controlled using a Camera.Parameters object. You obtain this object past beginning getting an instance of the Camera object, calling the getParameters() method, changing the returned parameter object and then setting information technology back into the camera object, as demonstrated in the following case code:

Kotlin

val params: Photographic camera.Parameters? = camera?.parameters params?.focusMode = Camera.Parameters.FOCUS_MODE_AUTO camera?.parameters = params            

Coffee

// get Camera parameters Camera.Parameters params = camera.getParameters(); // set the focus mode params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); // set up Camera parameters camera.setParameters(params);            

This technique works for well-nigh all camera features, and almost parameters can exist changed at any fourth dimension after you lot have obtained an example of the Camera object. Changes to parameters are typically visible to the user immediately in the awarding's camera preview. On the software side, parameter changes may take several frames to actually take effect as the photographic camera hardware processes the new instructions and and then sends updated image data.

Important: Some photographic camera features cannot be inverse at will. In particular, irresolute the size or orientation of the camera preview requires that you outset stop the preview, change the preview size, and and so restart the preview. Starting with Android four.0 (API Level fourteen) preview orientation can be changed without restarting the preview.

Other camera features require more code in order to implement, including:

  • Metering and focus areas
  • Face detection
  • Time lapse video

A quick outline of how to implement these features is provided in the following sections.

Metering and focus areas

In some photographic scenarios, automatic focusing and low-cal metering may not produce the desired results. Starting with Android iv.0 (API Level fourteen), your photographic camera application can provide additional controls to permit your app or users to specify areas in an image to use for determining focus or light level settings and pass these values to the photographic camera hardware for use in capturing images or video.

Areas for metering and focus work very similarly to other camera features, in that you lot control them through methods in the Camera.Parameters object. The post-obit code demonstrates setting ii light metering areas for an example of Photographic camera:

Kotlin

// Create an instance of Camera camera = getCameraInstance()  // ready Camera parameters val params: Camera.Parameters? = camera?.parameters  params?.apply {     if (maxNumMeteringAreas > 0) { // check that metering areas are supported         meteringAreas = ArrayList<Photographic camera.Area>().apply {             val areaRect1 = Rect(-100, -100, 100, 100) // specify an area in center of prototype             add(Camera.Area(areaRect1, 600)) // gear up weight to lx%             val areaRect2 = Rect(800, -k, 1000, -800) // specify an area in upper right of paradigm             add(Camera.Area(areaRect2, 400)) // prepare weight to forty%         }     }     photographic camera?.parameters = this }            

Coffee

// Create an instance of Camera photographic camera = getCameraInstance();  // set Camera parameters Camera.Parameters params = camera.getParameters();  if (params.getMaxNumMeteringAreas() > 0){ // cheque that metering areas are supported     List<Camera.Area> meteringAreas = new ArrayList<Photographic camera.Surface area>();      Rect areaRect1 = new Rect(-100, -100, 100, 100);    // specify an surface area in middle of image     meteringAreas.add(new Camera.Area(areaRect1, 600)); // set weight to lx%     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 twoscore%     params.setMeteringAreas(meteringAreas); }  photographic camera.setParameters(params);            

The Camera.Area object contains two data parameters: A Rect object for specifying an surface area within the camera'due south field of view and a weight value, which tells the camera what level of importance this area should exist given in light metering or focus calculations.

The Rect field in a Camera.Surface area object describes a rectangular shape mapped on a 2000 10 2000 unit filigree. The coordinates -1000, -m represent the top, left corner of the camera image, and coordinates 1000, one thousand represent the bottom, correct corner of the camera image, as shown in the illustration below.

Figure 1. The cherry lines illustrate the coordinate arrangement for specifying a Camera.Expanse inside a photographic camera preview. The blue box shows the location and shape of an camera surface area with the Rect values 333,333,667,667.

The bounds of this coordinate system always represent to the outer edge of the paradigm visible in the photographic camera preview and practise not compress or expand with the zoom level. Similarly, rotation of the image preview using Photographic camera.setDisplayOrientation() does not remap the coordinate organization.

Face detection

For pictures that include people, faces are unremarkably the most of import part of the picture, and should be used for determining both focus and white residue when capturing an paradigm. The Android 4.0 (API Level 14) framework provides APIs for identifying faces and calculating flick settings using face recognition technology.

Note: While the face detection feature is running, setWhiteBalance(String), setFocusAreas(Listing<Camera.Area>) and setMeteringAreas(List<Camera.Area>) have no effect.

Using the face detection characteristic in your camera awarding requires a few general steps:

  • Check that face detection is supported on the device
  • Create a face detection listener
  • Add the face detection listener to your photographic camera object
  • Start face detection after preview (and after every preview restart)

The face detection feature is non supported on all devices. Yous can cheque that this feature is supported by calling getMaxNumDetectedFaces(). An example of this check is shown in the startFaceDetection() sample method below.

In order to be notified and answer to the detection of a face, your camera application must set a listener for face detection events. In society to do this, you must create a listener grade that implements the Camera.FaceDetectionListener interface equally shown in the instance code below.

Kotlin

internal class MyFaceDetectionListener : Camera.FaceDetectionListener {      override fun onFaceDetection(faces: Array<Camera.Confront>, photographic camera: Camera) {         if (faces.isNotEmpty()) {             Log.d("FaceDetection", ("face detected: ${faces.size}" +                     " Confront one 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 up i Location X: " + faces[0].rect.centerX() +                     "Y: " + faces[0].rect.centerY() );         }     } }            

After creating this course, you then ready it into your application'south Camera object, as shown in the case code beneath:

Kotlin

camera?.setFaceDetectionListener(MyFaceDetectionListener())            

Java

camera.setFaceDetectionListener(new MyFaceDetectionListener());            

Your awarding must beginning the face detection function each time you showtime (or restart) the camera preview. Create a method for starting face detection so you lot tin can telephone call it as needed, as shown in the example code below.

Kotlin

fun startFaceDetection() {     // Try starting Face Detection     val params = mCamera?.parameters     // get-go confront detection only *after* preview has started      params?.apply {         if (maxNumDetectedFaces > 0) {             // photographic camera supports face detection, so tin offset it:             mCamera?.startFaceDetection()         }     } }            

Java

public void startFaceDetection(){     // Endeavour starting Confront Detection     Camera.Parameters params = mCamera.getParameters();      // start face detection simply *after* preview has started     if (params.getMaxNumDetectedFaces() > 0){         // photographic camera supports face detection, and so can start it:         mCamera.startFaceDetection();     } }            

You lot must get-go face detection each time you start (or restart) the camera preview. If you lot utilize the preview class shown in Creating a preview class, add your startFaceDetection() method to both the surfaceCreated() and surfaceChanged() methods in your preview class, as shown in the sample code below.

Kotlin

override fun surfaceCreated(holder: SurfaceHolder) {     try {         mCamera.setPreviewDisplay(holder)         mCamera.startPreview()          startFaceDetection() // start face up detection characteristic     } catch (e: IOException) {         Log.d(TAG, "Error setting camera preview: ${east.message}")     } }  override fun surfaceChanged(holder: SurfaceHolder, format: Int, due west: Int, h: Int) {     if (holder.surface == null) {         // preview surface does not exist         Log.d(TAG, "holder.getSurface() == null")         return     }     try {         mCamera.stopPreview()     } grab (e: Exception) {         // ignore: tried to stop a non-existent preview         Log.d(TAG, "Mistake stopping camera preview: ${eastward.message}")     }     try {         mCamera.setPreviewDisplay(holder)         mCamera.startPreview()          startFaceDetection() // re-offset face up detection characteristic     } 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(); // first confront detection feature      } catch (IOException e) {         Log.d(TAG, "Fault 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();      } take hold of (Exception e){         // ignore: tried to terminate a non-existent preview         Log.d(TAG, "Error stopping camera preview: " + eastward.getMessage());     }      try {         mCamera.setPreviewDisplay(holder);         mCamera.startPreview();          startFaceDetection(); // re-outset face up detection feature      } catch (Exception e){         // ignore: tried to stop a non-existent preview         Log.d(TAG, "Mistake starting camera preview: " + eastward.getMessage());     } }            

Note: Remember to call this method after calling startPreview(). Do non try to start face detection in the onCreate() method of your camera app'due south main activity, every bit the preview is non available past this point in your application'south the execution.

Fourth dimension lapse video

Time lapse video allows users to create video clips that combine pictures taken a few seconds or minutes apart. This characteristic uses MediaRecorder to record the images for a time lapse sequence.

To record a fourth dimension lapse video with MediaRecorder, you must configure the recorder object as if you are recording a normal video, setting the captured frames per second to a low number and using one of the time lapse quality settings, equally shown in the code example below.

Kotlin

mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_TIME_LAPSE_HIGH)) mediaRecorder.setCaptureRate(0.1) // capture a frame every 10 seconds            

Java

// Step iii: Set a CamcorderProfile (requires API Level 8 or higher) mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_TIME_LAPSE_HIGH)); ... // Stride 5.five: Ready the video capture rate to a low number mediaRecorder.setCaptureRate(0.1); // capture a frame every x seconds            

These settings must exist done equally part of a larger configuration procedure for MediaRecorder. For a full configuration code example, come across Configuring MediaRecorder. Once the configuration is complete, yous starting time the video recording every bit if you lot were recording a normal video prune. For more information about configuring and running MediaRecorder, see Capturing videos.

The Camera2Video and HdrViewfinder samples further demonstrate the use of the APIs covered on this page.

Camera fields that crave permission

Apps running Android x (API level 29) or higher must have the Camera permission in gild to access the values of the following fields that the getCameraCharacteristics() method returns:

  • 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 lawmaking

To download sample apps, see the Camera2Basic sample and Official CameraX sample app.

Source: https://developer.android.com/guide/topics/media/camera

Posted by: toddafrourned.blogspot.com

0 Response to "Do I Need Camera Permission For Take A Picture Android"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel