1page.title=Camera 2page.tags=photo,video,picture,mediarecorder 3@jd:body 4 5<div id="qv-wrapper"> 6 <div id="qv"> 7 <h2>In this document</h2> 8 <ol> 9 <li><a href="#considerations">Considerations</a></li> 10 <li><a href="#basics">The Basics</a> 11 <li><a href="#manifest">Manifest Declarations</a></li> 12 <li><a href="#camera-apps">Using Existing Camera Apps</a> 13 <li><a href="#custom-camera">Building a Camera App</a> 14 <ol> 15 <li><a href="#detect-camera">Detecting camera hardware</a></li> 16 <li><a href="#access-camera">Accessing cameras</a></li> 17 <li><a href="#check-camera-features">Checking camera features</a></li> 18 <li><a href="#camera-preview">Creating a preview class</a></li> 19 <li><a href="#preview-layout">Placing preview in a layout</a></li> 20 <li><a href="#capture-picture">Capturing pictures</a></li> 21 <li><a href="#capture-video">Capturing videos</a></li> 22 <li><a href="#release-camera">Releasing the camera</a></li> 23 </ol> 24 </li> 25 <li><a href="#saving-media">Saving Media Files</a></li> 26 <li><a href="#camera-features">Camera Features</a> 27 <ol> 28 <li><a href="#check-feature">Checking feature availability</a></li> 29 <li><a href="#using-features">Using camera features</a></li> 30 <li><a href="#metering-focus-areas">Metering and focus areas</a></li> 31 <li><a href="#face-detection">Face detection</a></li> 32 <li><a href="#time-lapse-video">Time lapse video</a></li> 33 </ol> 34 </li> 35 </ol> 36 <h2>Key Classes</h2> 37 <ol> 38 <li>{@link android.hardware.Camera}</li> 39 <li>{@link android.view.SurfaceView}</li> 40 <li>{@link android.media.MediaRecorder}</li> 41 <li>{@link android.content.Intent}</li> 42 </ol> 43 <h2>See also</h2> 44 <ol> 45 <li><a href="{@docRoot}guide/topics/media/mediaplayer.html">Media Playback</a></li> 46 <li><a href="{@docRoot}guide/topics/data/data-storage.html">Data Storage</a></li> 47 </ol> 48 </div> 49</div> 50 51 52<p>The Android framework includes support for various cameras and camera features available on 53devices, allowing you to capture pictures and videos in your applications. This document discusses a 54quick, simple approach to image and video capture and outlines an advanced approach for creating 55custom camera experiences for your users.</p> 56 57<h2 id="considerations">Considerations</h2> 58<p>Before enabling your application to use cameras on Android devices, you should consider a few 59questions about how your app intends to use this hardware feature.</p> 60 61<ul> 62 <li><strong>Camera Requirement</strong> - Is the use of a camera so important to your 63application that you do not want your application installed on a device that does not have a 64camera? If so, you should declare the <a href="#manifest">camera requirement in your 65manifest</a>.</li> 66 67 <li><strong>Quick Picture or Customized Camera</strong> - How will your application use the 68camera? Are you just interested in snapping a quick picture or video clip, or will your application 69provide a new way to use cameras? For a getting a quick snap or clip, consider 70<a href="#camera-apps">Using Existing Camera Apps</a>. For developing a customized camera feature, check 71out the <a href="#custom-camera">Building a Camera App</a> section.</li> 72 73 <li><strong>Storage</strong> - Are the images or videos your application generates intended to be 74only visible to your application or shared so that other applications such as Gallery or other 75media and social apps can use them? Do you want the pictures and videos to be available even if your 76application is uninstalled? Check out the <a href="#saving-media">Saving Media Files</a> section to 77see how to implement these options.</li> 78</ul> 79 80 81 82<h2 id="basics">The Basics</h2> 83<p>The Android framework supports capturing images and video through the 84{@link android.hardware.camera2} API or camera {@link android.content.Intent}. Here are the relevant 85classes:</p> 86 87<dl> 88 <dt>{@link android.hardware.camera2}</dt> 89 <dd>This package is the primary API for controlling device cameras. It can be used to take 90pictures or videos when you are building a camera application.</dd> 91 92 <dt>{@link android.hardware.Camera}</dt> 93 <dd>This class is the older deprecated API for controlling device cameras.</dd> 94 95 <dt>{@link android.view.SurfaceView}</dt> 96 <dd>This class is used to present a live camera preview to the user.</dd> 97 98 <dt>{@link android.media.MediaRecorder}</dt> 99 <dd>This class is used to record video from the camera.</dd> 100 101 <dt>{@link android.content.Intent}</dt> 102 <dd>An intent action type of {@link android.provider.MediaStore#ACTION_IMAGE_CAPTURE 103MediaStore.ACTION_IMAGE_CAPTURE} or {@link android.provider.MediaStore#ACTION_VIDEO_CAPTURE 104MediaStore.ACTION_VIDEO_CAPTURE} can be used to capture images or videos without directly 105using the {@link android.hardware.Camera} object.</dd> 106</dl> 107 108 109<h2 id="manifest">Manifest Declarations</h2> 110<p>Before starting development on your application with the Camera API, you should make sure 111your manifest has the appropriate declarations to allow use of camera hardware and other 112related features.</p> 113 114<ul> 115 <li><strong>Camera Permission</strong> - Your application must request permission to use a device 116camera. 117<pre> 118<uses-permission android:name="android.permission.CAMERA" /> 119</pre> 120 <p class="note"><strong>Note:</strong> If you are using the camera <a href="#camera-apps">by 121invoking an existing camera app</a>, 122your application does not need to request this permission.</p> 123 </li> 124 <li><strong>Camera Features</strong> - Your application must also declare use of camera features, 125for example: 126<pre> 127<uses-feature android:name="android.hardware.camera" /> 128</pre> 129 <p>For a list of camera features, see the manifest 130<a href="{@docRoot}guide/topics/manifest/uses-feature-element.html#hw-features">Features 131Reference</a>.</p> 132 <p>Adding camera features to your manifest causes Google Play to prevent your application from 133being installed to devices that do not include a camera or do not support the camera features you 134specify. For more information about using feature-based filtering with Google Play, see <a 135href="{@docRoot}guide/topics/manifest/uses-feature-element.html#market-feature-filtering">Google 136Play and Feature-Based Filtering</a>.</p> 137 <p>If your application <em>can use</em> a camera or camera feature for proper operation, but does 138not <em>require</em> it, you should specify this in the manifest by including the {@code 139android:required} attribute, and setting it to {@code false}:</p> 140<pre> 141<uses-feature android:name="android.hardware.camera" android:required="false" /> 142</pre> 143 144 </li> 145 <li><strong>Storage Permission</strong> - If your application saves images or videos to the 146device's external storage (SD Card), you must also specify this in the manifest. 147<pre> 148<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 149</pre> 150 </li> 151 <li><strong>Audio Recording Permission</strong> - For recording audio with video capture, your 152application must request the audio capture permission. 153<pre> 154<uses-permission android:name="android.permission.RECORD_AUDIO" /> 155</pre> 156 </li> 157 <li> 158 <p><strong>Location Permission</strong> - If your application tags images 159 with GPS location information, you must request the {@code ACCESS_FINE_LOCATION} 160 permission. Note that, if your app targets Android 5.0 (API level 21) or 161 higher, you also need to declare that your app uses the device's GPS:</p> 162<pre> 163<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 164... 165<!-- Needed only if your app targets Android 5.0 (API level 21) or higher. --> 166<uses-feature android:name="android.hardware.location.gps" /> 167</pre> 168<p>For more information about getting user location, see 169<a href="{@docRoot}guide/topics/location/strategies.html">Location Strategies</a>.</p> 170 </li> 171</ul> 172 173 174<h2 id="camera-apps">Using Existing Camera Apps</h2> 175<p>A quick way to enable taking pictures or videos in your application without a lot of extra code 176is to use an {@link android.content.Intent} to invoke an existing Android camera application. 177The details are described in the training lessons 178<a href="{@docRoot}training/camera/photobasics.html">Taking Photos Simply</a> and 179<a href="{@docRoot}training/camera/videobasics.html">Recording Videos Simply</a>.</p> 180 181<h2 id="custom-camera">Building a Camera App</h2> 182<p>Some developers may require a camera user interface that is customized to the look of their 183application or provides special features. Writing your own picture-taking code 184can provide a more compelling experience for your users.</p> 185 186<p><strong> Note: The following guide is for the older, deprecated {@link android.hardware.Camera} 187API. For new or advanced camera applications, the newer {@link android.hardware.camera2} API is 188recommended.</strong></p> 189 190<p>The general steps for creating a custom camera interface for your application are as follows:</p> 191 192<ul> 193 <li><strong>Detect and Access Camera</strong> - Create code to check for the existence of 194cameras and request access.</li> 195 <li><strong>Create a Preview Class</strong> - Create a camera preview class that extends {@link 196android.view.SurfaceView} and implements the {@link android.view.SurfaceHolder} interface. This 197class previews the live images from the camera.</li> 198 <li><strong>Build a Preview Layout</strong> - Once you have the camera preview class, create a 199view layout that incorporates the preview and the user interface controls you want.</li> 200 <li><strong>Setup Listeners for Capture</strong> - Connect listeners for your interface 201controls to start image or video capture in response to user actions, such as pressing a 202button.</li> 203 <li><strong>Capture and Save Files</strong> - Setup the code for capturing pictures or 204videos and saving the output.</li> 205 <li><strong>Release the Camera</strong> - After using the camera, your application must 206properly release it for use by other applications.</li> 207</ul> 208 209<p>Camera hardware is a shared resource that must be carefully managed so your application does 210not collide with other applications that may also want to use it. The following sections discusses 211how to detect camera hardware, how to request access to a camera, how to capture pictures or video 212and how to release the camera when your application is done using it.</p> 213 214<p class="caution"><strong>Caution:</strong> Remember to release the {@link android.hardware.Camera} 215object by calling the {@link android.hardware.Camera#release() Camera.release()} when your 216application is done using it! If your application does not properly release the camera, all 217subsequent attempts to access the camera, including those by your own application, will fail and may 218cause your or other applications to be shut down.</p> 219 220 221<h3 id="detect-camera">Detecting camera hardware</h3> 222<p>If your application does not specifically require a camera using a manifest declaration, you 223should check to see if a camera is available at runtime. To perform this check, use the {@link 224android.content.pm.PackageManager#hasSystemFeature(java.lang.String) 225PackageManager.hasSystemFeature()} method, as shown in the example code below:</p> 226 227<pre> 228/** Check if this device has a camera */ 229private boolean checkCameraHardware(Context context) { 230 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){ 231 // this device has a camera 232 return true; 233 } else { 234 // no camera on this device 235 return false; 236 } 237} 238</pre> 239 240<p>Android devices can have multiple cameras, for example a back-facing camera for photography and a 241front-facing camera for video calls. Android 2.3 (API Level 9) and later allows you to check the 242number of cameras available on a device using the {@link 243android.hardware.Camera#getNumberOfCameras() Camera.getNumberOfCameras()} method.</p> 244 245<h3 id="access-camera">Accessing cameras</h3> 246<p>If you have determined that the device on which your application is running has a camera, you 247must request to access it by getting an instance of {@link android.hardware.Camera} (unless you 248are using an <a href="camera-apps">intent to access the camera</a>). </p> 249 250<p>To access the primary camera, use the {@link android.hardware.Camera#open() Camera.open()} method 251and be sure to catch any exceptions, as shown in the code below:</p> 252 253<pre> 254/** A safe way to get an instance of the Camera object. */ 255public static Camera getCameraInstance(){ 256 Camera c = null; 257 try { 258 c = Camera.open(); // attempt to get a Camera instance 259 } 260 catch (Exception e){ 261 // Camera is not available (in use or does not exist) 262 } 263 return c; // returns null if camera is unavailable 264} 265</pre> 266 267<p class="caution"><strong>Caution:</strong> Always check for exceptions when using {@link 268android.hardware.Camera#open() Camera.open()}. Failing to check for exceptions if the camera is in 269use or does not exist will cause your application to be shut down by the system.</p> 270 271<p>On devices running Android 2.3 (API Level 9) or higher, you can access specific cameras using 272{@link android.hardware.Camera#open(int) Camera.open(int)}. The example code above will access 273the first, back-facing camera on a device with more than one camera.</p> 274 275<h3 id="check-camera-features">Checking camera features</h3> 276<p>Once you obtain access to a camera, you can get further information about its capabilities using 277the {@link android.hardware.Camera#getParameters() Camera.getParameters()} method and checking the 278returned {@link android.hardware.Camera.Parameters} object for supported capabilities. When using 279API Level 9 or higher, use the {@link android.hardware.Camera#getCameraInfo(int, 280android.hardware.Camera.CameraInfo) Camera.getCameraInfo()} to determine if a camera is on the front 281or back of the device, and the orientation of the image.</p> 282 283 284 285<h3 id="camera-preview">Creating a preview class</h3> 286<p>For users to effectively take pictures or video, they must be able to see what the device camera 287sees. A camera preview class is a {@link android.view.SurfaceView} that can display the live image 288data coming from a camera, so users can frame and capture a picture or video.</p> 289 290<p>The following example code demonstrates how to create a basic camera preview class that can be 291included in a {@link android.view.View} layout. This class implements {@link 292android.view.SurfaceHolder.Callback SurfaceHolder.Callback} in order to capture the callback events 293for creating and destroying the view, which are needed for assigning the camera preview input.</p> 294 295<pre> 296/** A basic Camera preview class */ 297public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { 298 private SurfaceHolder mHolder; 299 private Camera mCamera; 300 301 public CameraPreview(Context context, Camera camera) { 302 super(context); 303 mCamera = camera; 304 305 // Install a SurfaceHolder.Callback so we get notified when the 306 // underlying surface is created and destroyed. 307 mHolder = getHolder(); 308 mHolder.addCallback(this); 309 // deprecated setting, but required on Android versions prior to 3.0 310 mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 311 } 312 313 public void surfaceCreated(SurfaceHolder holder) { 314 // The Surface has been created, now tell the camera where to draw the preview. 315 try { 316 mCamera.setPreviewDisplay(holder); 317 mCamera.startPreview(); 318 } catch (IOException e) { 319 Log.d(TAG, "Error setting camera preview: " + e.getMessage()); 320 } 321 } 322 323 public void surfaceDestroyed(SurfaceHolder holder) { 324 // empty. Take care of releasing the Camera preview in your activity. 325 } 326 327 public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { 328 // If your preview can change or rotate, take care of those events here. 329 // Make sure to stop the preview before resizing or reformatting it. 330 331 if (mHolder.getSurface() == null){ 332 // preview surface does not exist 333 return; 334 } 335 336 // stop preview before making changes 337 try { 338 mCamera.stopPreview(); 339 } catch (Exception e){ 340 // ignore: tried to stop a non-existent preview 341 } 342 343 // set preview size and make any resize, rotate or 344 // reformatting changes here 345 346 // start preview with new settings 347 try { 348 mCamera.setPreviewDisplay(mHolder); 349 mCamera.startPreview(); 350 351 } catch (Exception e){ 352 Log.d(TAG, "Error starting camera preview: " + e.getMessage()); 353 } 354 } 355} 356</pre> 357 358<p>If you want to set a specific size for your camera preview, set this in the {@code 359surfaceChanged()} method as noted in the comments above. When setting preview size, you 360<em>must use</em> values from {@link android.hardware.Camera.Parameters#getSupportedPreviewSizes}. 361<em>Do not</em> set arbitrary values in the {@link 362android.hardware.Camera.Parameters#setPreviewSize setPreviewSize()} method.</p> 363 364 365<h3 id="preview-layout">Placing preview in a layout</h3> 366<p>A camera preview class, such as the example shown in the previous section, must be placed in the 367layout of an activity along with other user interface controls for taking a picture or video. This 368section shows you how to build a basic layout and activity for the preview.</p> 369 370<p>The following layout code provides a very basic view that can be used to display a camera 371preview. In this example, the {@link android.widget.FrameLayout} element is meant to be the 372container for the camera preview class. This layout type is used so that additional picture 373information or controls can be overlayed on the live camera preview images.</p> 374 375<pre> 376<?xml version="1.0" encoding="utf-8"?> 377<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 378 android:orientation="horizontal" 379 android:layout_width="fill_parent" 380 android:layout_height="fill_parent" 381 > 382 <FrameLayout 383 android:id="@+id/camera_preview" 384 android:layout_width="fill_parent" 385 android:layout_height="fill_parent" 386 android:layout_weight="1" 387 /> 388 389 <Button 390 android:id="@+id/button_capture" 391 android:text="Capture" 392 android:layout_width="wrap_content" 393 android:layout_height="wrap_content" 394 android:layout_gravity="center" 395 /> 396</LinearLayout> 397</pre> 398 399<p>On most devices, the default orientation of the camera preview is landscape. This example layout 400specifies a horizontal (landscape) layout and the code below fixes the orientation of the 401application to landscape. For simplicity in rendering a camera preview, you should change your 402application's preview activity orientation to landscape by adding the following to your 403manifest.</p> 404 405<pre> 406<activity android:name=".CameraActivity" 407 android:label="@string/app_name" 408 409 android:screenOrientation="landscape"> 410 <!-- configure this activity to use landscape orientation --> 411 412 <intent-filter> 413 <action android:name="android.intent.action.MAIN" /> 414 <category android:name="android.intent.category.LAUNCHER" /> 415 </intent-filter> 416</activity> 417</pre> 418 419<p class="note"><strong>Note:</strong> A camera preview does not have to be in landscape mode. 420Starting in Android 2.2 (API Level 8), you can use the {@link 421android.hardware.Camera#setDisplayOrientation(int) setDisplayOrientation()} method to set the 422rotation of the preview image. In order to change preview orientation as the user re-orients the 423phone, within the {@link 424android.view.SurfaceHolder.Callback#surfaceChanged(android.view.SurfaceHolder, int, int, int) 425surfaceChanged()} method of your preview class, first stop the preview with {@link 426android.hardware.Camera#stopPreview() Camera.stopPreview()} change the orientation and then 427start the preview again with {@link android.hardware.Camera#startPreview() 428Camera.startPreview()}.</p> 429 430<p>In the activity for your camera view, add your preview class to the {@link 431android.widget.FrameLayout} element shown in the example above. Your camera activity must also 432ensure that it releases the camera when it is paused or shut down. The following example shows how 433to modify a camera activity to attach the preview class shown in <a href="#camera-preview">Creating 434a preview class</a>.</p> 435 436<pre> 437public class CameraActivity extends Activity { 438 439 private Camera mCamera; 440 private CameraPreview mPreview; 441 442 @Override 443 public void onCreate(Bundle savedInstanceState) { 444 super.onCreate(savedInstanceState); 445 setContentView(R.layout.main); 446 447 // Create an instance of Camera 448 mCamera = getCameraInstance(); 449 450 // Create our Preview view and set it as the content of our activity. 451 mPreview = new CameraPreview(this, mCamera); 452 FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview); 453 preview.addView(mPreview); 454 } 455} 456</pre> 457 458<p class="note"><strong>Note:</strong> The {@code getCameraInstance()} method in the example above 459refers to the example method shown in <a href="#access-camera">Accessing cameras</a>.</p> 460 461 462<h3 id="capture-picture">Capturing pictures</h3> 463<p>Once you have built a preview class and a view layout in which to display it, you are ready to 464start capturing images with your application. In your application code, you must set up listeners 465for your user interface controls to respond to a user action by taking a picture.</p> 466 467<p>In order to retrieve a picture, use the {@link 468android.hardware.Camera#takePicture(android.hardware.Camera.ShutterCallback, 469android.hardware.Camera.PictureCallback, android.hardware.Camera.PictureCallback) 470Camera.takePicture()} method. This method takes three parameters which receive data from the camera. 471In order to receive data in a JPEG format, you must implement an {@link 472android.hardware.Camera.PictureCallback} interface to receive the image data and 473write it to a file. The following code shows a basic implementation of the {@link 474android.hardware.Camera.PictureCallback} interface to save an image received from the camera.</p> 475 476<pre> 477private PictureCallback mPicture = new PictureCallback() { 478 479 @Override 480 public void onPictureTaken(byte[] data, Camera camera) { 481 482 File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE); 483 if (pictureFile == null){ 484 Log.d(TAG, "Error creating media file, check storage permissions: " + 485 e.getMessage()); 486 return; 487 } 488 489 try { 490 FileOutputStream fos = new FileOutputStream(pictureFile); 491 fos.write(data); 492 fos.close(); 493 } catch (FileNotFoundException e) { 494 Log.d(TAG, "File not found: " + e.getMessage()); 495 } catch (IOException e) { 496 Log.d(TAG, "Error accessing file: " + e.getMessage()); 497 } 498 } 499}; 500</pre> 501 502<p>Trigger capturing an image by calling the {@link 503android.hardware.Camera#takePicture(android.hardware.Camera.ShutterCallback, 504android.hardware.Camera.PictureCallback, android.hardware.Camera.PictureCallback) 505Camera.takePicture()} method. The following example code shows how to call this method from a 506button {@link android.view.View.OnClickListener}.</p> 507 508<pre> 509// Add a listener to the Capture button 510Button captureButton = (Button) findViewById(id.button_capture); 511captureButton.setOnClickListener( 512 new View.OnClickListener() { 513 @Override 514 public void onClick(View v) { 515 // get an image from the camera 516 mCamera.takePicture(null, null, mPicture); 517 } 518 } 519); 520</pre> 521 522<p class="note"><strong>Note:</strong> The {@code mPicture} member in the following example refers 523to the example code above.</p> 524 525<p class="caution"><strong>Caution:</strong> Remember to release the {@link android.hardware.Camera} 526object by calling the {@link android.hardware.Camera#release() Camera.release()} when your 527application is done using it! For information about how to release the camera, see <a 528href="#release-camera">Releasing the camera</a>.</p> 529 530 531<h3 id="capture-video">Capturing videos</h3> 532 533<p>Video capture using the Android framework requires careful management of the {@link 534android.hardware.Camera} object and coordination with the {@link android.media.MediaRecorder} 535class. When recording video with {@link android.hardware.Camera}, you must manage the {@link 536android.hardware.Camera#lock() Camera.lock()} and {@link android.hardware.Camera#unlock() 537Camera.unlock()} calls to allow {@link android.media.MediaRecorder} access to the camera hardware, 538in addition to the {@link android.hardware.Camera#open() Camera.open()} and {@link 539android.hardware.Camera#release() Camera.release()} calls.</p> 540 541<p class="note"><strong>Note:</strong> Starting with Android 4.0 (API level 14), the {@link 542android.hardware.Camera#lock() Camera.lock()} and {@link android.hardware.Camera#unlock() 543Camera.unlock()} calls are managed for you automatically.</p> 544 545<p>Unlike taking pictures with a device camera, capturing video requires a very particular call 546order. You must follow a specific order of execution to successfully prepare for and capture video 547with your application, as detailed below.</p> 548 549<ol> 550 <li><strong>Open Camera</strong> - Use the {@link android.hardware.Camera#open() Camera.open()} 551to get an instance of the camera object.</li> 552 <li><strong>Connect Preview</strong> - Prepare a live camera image preview by connecting a {@link 553android.view.SurfaceView} to the camera using {@link 554android.hardware.Camera#setPreviewDisplay(android.view.SurfaceHolder) Camera.setPreviewDisplay()}. 555 </li> 556 <li><strong>Start Preview</strong> - Call {@link android.hardware.Camera#startPreview() 557Camera.startPreview()} to begin displaying the live camera images.</li> 558 <li><strong>Start Recording Video</strong> - The following steps must be completed <em>in 559order</em> to successfully record video: 560 <ol style="list-style-type: lower-alpha;"> 561 <li><strong>Unlock the Camera</strong> - Unlock the camera for use by {@link 562android.media.MediaRecorder} by calling {@link android.hardware.Camera#unlock() 563Camera.unlock()}.</li> 564 <li><strong>Configure MediaRecorder</strong> - Call in the following {@link 565android.media.MediaRecorder} methods <em>in this order</em>. For more information, see the {@link 566android.media.MediaRecorder} reference documentation. 567 <ol> 568 <li>{@link android.media.MediaRecorder#setCamera(android.hardware.Camera) 569setCamera()} - Set the camera to be used for video capture, use your application's current instance 570of {@link android.hardware.Camera}.</li> 571 <li>{@link android.media.MediaRecorder#setAudioSource(int) setAudioSource()} - Set the 572audio source, use {@link android.media.MediaRecorder.AudioSource#CAMCORDER 573MediaRecorder.AudioSource.CAMCORDER}. </li> 574 <li>{@link android.media.MediaRecorder#setVideoSource(int) setVideoSource()} - Set 575the video source, use {@link android.media.MediaRecorder.VideoSource#CAMERA 576MediaRecorder.VideoSource.CAMERA}.</li> 577 <li>Set the video output format and encoding. For Android 2.2 (API Level 8) and 578higher, use the {@link android.media.MediaRecorder#setProfile(android.media.CamcorderProfile) 579MediaRecorder.setProfile} method, and get a profile instance using {@link 580android.media.CamcorderProfile#get(int) CamcorderProfile.get()}. For versions of Android prior to 5812.2, you must set the video output format and encoding parameters: 582 <ol style="list-style-type: lower-roman;"> 583 <li>{@link android.media.MediaRecorder#setOutputFormat(int) setOutputFormat()} - Set 584the output format, specify the default setting or {@link 585android.media.MediaRecorder.OutputFormat#MPEG_4 MediaRecorder.OutputFormat.MPEG_4}.</li> 586 <li>{@link android.media.MediaRecorder#setAudioEncoder(int) setAudioEncoder()} - Set 587the sound encoding type, specify the default setting or {@link 588android.media.MediaRecorder.AudioEncoder#AMR_NB MediaRecorder.AudioEncoder.AMR_NB}.</li> 589 <li>{@link android.media.MediaRecorder#setVideoEncoder(int) setVideoEncoder()} - Set 590the video encoding type, specify the default setting or {@link 591android.media.MediaRecorder.VideoEncoder#MPEG_4_SP MediaRecorder.VideoEncoder.MPEG_4_SP}.</li> 592 </ol> 593 </li> 594 <li>{@link android.media.MediaRecorder#setOutputFile(java.lang.String) setOutputFile()} - 595Set the output file, use {@code getOutputMediaFile(MEDIA_TYPE_VIDEO).toString()} from the example 596method in the <a href="#saving-media">Saving Media Files</a> section.</li> 597 <li>{@link android.media.MediaRecorder#setPreviewDisplay(android.view.Surface) 598setPreviewDisplay()} - Specify the {@link android.view.SurfaceView} preview layout element for 599your application. Use the same object you specified for <strong>Connect Preview</strong>.</li> 600 </ol> 601 <p class="caution"><strong>Caution:</strong> You must call these {@link 602android.media.MediaRecorder} configuration methods <em>in this order</em>, otherwise your 603application will encounter errors and the recording will fail.</p> 604 </li> 605 <li><strong>Prepare MediaRecorder</strong> - Prepare the {@link android.media.MediaRecorder} 606with provided configuration settings by calling {@link android.media.MediaRecorder#prepare() 607MediaRecorder.prepare()}.</li> 608 <li><strong>Start MediaRecorder</strong> - Start recording video by calling {@link 609android.media.MediaRecorder#start() MediaRecorder.start()}.</li> 610 </ol> 611 </li> 612 <li><strong>Stop Recording Video</strong> - Call the following methods <em>in order</em>, to 613successfully complete a video recording: 614 <ol style="list-style-type: lower-alpha;"> 615 <li><strong>Stop MediaRecorder</strong> - Stop recording video by calling {@link 616android.media.MediaRecorder#stop() MediaRecorder.stop()}.</li> 617 <li><strong>Reset MediaRecorder</strong> - Optionally, remove the configuration settings from 618the recorder by calling {@link android.media.MediaRecorder#reset() MediaRecorder.reset()}.</li> 619 <li><strong>Release MediaRecorder</strong> - Release the {@link android.media.MediaRecorder} 620by calling {@link android.media.MediaRecorder#release() MediaRecorder.release()}.</li> 621 <li><strong>Lock the Camera</strong> - Lock the camera so that future {@link 622android.media.MediaRecorder} sessions can use it by calling {@link android.hardware.Camera#lock() 623Camera.lock()}. Starting with Android 4.0 (API level 14), this call is not required unless the 624{@link android.media.MediaRecorder#prepare() MediaRecorder.prepare()} call fails.</li> 625 </ol> 626 </li> 627 <li><strong>Stop the Preview</strong> - When your activity has finished using the camera, stop the 628preview using {@link android.hardware.Camera#stopPreview() Camera.stopPreview()}.</li> 629 <li><strong>Release Camera</strong> - Release the camera so that other applications can use 630it by calling {@link android.hardware.Camera#release() Camera.release()}.</li> 631</ol> 632 633<p class="note"><strong>Note:</strong> It is possible to use {@link android.media.MediaRecorder} 634without creating a camera preview first and skip the first few steps of this process. However, 635since users typically prefer to see a preview before starting a recording, that process is not 636discussed here.</p> 637 638<p class="note"><strong>Tip:</strong> If your application is typically used for recording video, set 639{@link android.hardware.Camera.Parameters#setRecordingHint} to {@code true} prior to starting your 640preview. This setting can help reduce the time it takes to start recording.</p> 641 642<h4 id="configuring-mediarecorder">Configuring MediaRecorder</h4> 643<p>When using the {@link android.media.MediaRecorder} class to record video, you must perform 644configuration steps in a <em>specific order</em> and then call the {@link 645android.media.MediaRecorder#prepare() MediaRecorder.prepare()} method to check and implement the 646configuration. The following example code demonstrates how to properly configure and prepare the 647{@link android.media.MediaRecorder} class for video recording.</p> 648 649<pre> 650private boolean prepareVideoRecorder(){ 651 652 mCamera = getCameraInstance(); 653 mMediaRecorder = new MediaRecorder(); 654 655 // Step 1: Unlock and set camera to MediaRecorder 656 mCamera.unlock(); 657 mMediaRecorder.setCamera(mCamera); 658 659 // Step 2: Set sources 660 mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER); 661 mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); 662 663 // Step 3: Set a CamcorderProfile (requires API Level 8 or higher) 664 mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH)); 665 666 // Step 4: Set output file 667 mMediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString()); 668 669 // Step 5: Set the preview output 670 mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface()); 671 672 // Step 6: Prepare configured MediaRecorder 673 try { 674 mMediaRecorder.prepare(); 675 } catch (IllegalStateException e) { 676 Log.d(TAG, "IllegalStateException preparing MediaRecorder: " + e.getMessage()); 677 releaseMediaRecorder(); 678 return false; 679 } catch (IOException e) { 680 Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage()); 681 releaseMediaRecorder(); 682 return false; 683 } 684 return true; 685} 686</pre> 687 688<p>Prior to Android 2.2 (API Level 8), you must set the output format and encoding formats 689parameters directly, instead of using {@link android.media.CamcorderProfile}. This approach is 690demonstrated in the following code:</p> 691 692<pre> 693 // Step 3: Set output format and encoding (for versions prior to API Level 8) 694 mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); 695 mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT); 696 mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT); 697</pre> 698 699<p>The following video recording parameters for {@link android.media.MediaRecorder} are given 700default settings, however, you may want to adjust these settings for your application:</p> 701 702<ul> 703 <li>{@link android.media.MediaRecorder#setVideoEncodingBitRate(int) 704setVideoEncodingBitRate()}</li> 705 <li>{@link android.media.MediaRecorder#setVideoSize(int, int) setVideoSize()}</li> 706 <li>{@link android.media.MediaRecorder#setVideoFrameRate(int) setVideoFrameRate()}</li> 707 <li>{@link android.media.MediaRecorder#setAudioEncodingBitRate(int) 708setAudioEncodingBitRate()}</li> <li>{@link android.media.MediaRecorder#setAudioChannels(int) 709setAudioChannels()}</li> 710 <li>{@link android.media.MediaRecorder#setAudioSamplingRate(int) setAudioSamplingRate()}</li> 711</ul> 712 713<h4 id="start-stop-mediarecorder">Starting and stopping MediaRecorder</h4> 714<p>When starting and stopping video recording using the {@link android.media.MediaRecorder} class, 715you must follow a specific order, as listed below.</p> 716 717<ol> 718 <li>Unlock the camera with {@link android.hardware.Camera#unlock() Camera.unlock()}</li> 719 <li>Configure {@link android.media.MediaRecorder} as shown in the code example above</li> 720 <li>Start recording using {@link android.media.MediaRecorder#start() 721MediaRecorder.start()}</li> 722 <li>Record the video</li> 723 <li>Stop recording using {@link 724android.media.MediaRecorder#stop() MediaRecorder.stop()}</li> 725 <li>Release the media recorder with {@link android.media.MediaRecorder#release() 726MediaRecorder.release()}</li> 727 <li>Lock the camera using {@link android.hardware.Camera#lock() Camera.lock()}</li> 728</ol> 729 730<p>The following example code demonstrates how to wire up a button to properly start and stop 731video recording using the camera and the {@link android.media.MediaRecorder} class.</p> 732 733<p class="note"><strong>Note:</strong> When completing a video recording, do not release the camera 734or else your preview will be stopped.</p> 735 736<pre> 737private boolean isRecording = false; 738 739// Add a listener to the Capture button 740Button captureButton = (Button) findViewById(id.button_capture); 741captureButton.setOnClickListener( 742 new View.OnClickListener() { 743 @Override 744 public void onClick(View v) { 745 if (isRecording) { 746 // stop recording and release camera 747 mMediaRecorder.stop(); // stop the recording 748 releaseMediaRecorder(); // release the MediaRecorder object 749 mCamera.lock(); // take camera access back from MediaRecorder 750 751 // inform the user that recording has stopped 752 setCaptureButtonText("Capture"); 753 isRecording = false; 754 } else { 755 // initialize video camera 756 if (prepareVideoRecorder()) { 757 // Camera is available and unlocked, MediaRecorder is prepared, 758 // now you can start recording 759 mMediaRecorder.start(); 760 761 // inform the user that recording has started 762 setCaptureButtonText("Stop"); 763 isRecording = true; 764 } else { 765 // prepare didn't work, release the camera 766 releaseMediaRecorder(); 767 // inform user 768 } 769 } 770 } 771 } 772); 773</pre> 774 775<p class="note"><strong>Note:</strong> In the above example, the {@code prepareVideoRecorder()} 776method refers to the example code shown in <a 777href="#configuring-mediarecorder">Configuring MediaRecorder</a>. This method takes care of locking 778the camera, configuring and preparing the {@link android.media.MediaRecorder} instance.</p> 779 780 781<h3 id="release-camera">Releasing the camera</h3> 782<p>Cameras are a resource that is shared by applications on a device. Your application can make 783use of the camera after getting an instance of {@link android.hardware.Camera}, and you must be 784particularly careful to release the camera object when your application stops using it, and as 785soon as your application is paused ({@link android.app.Activity#onPause() Activity.onPause()}). If 786your application does not properly release the camera, all subsequent attempts to access the camera, 787including those by your own application, will fail and may cause your or other applications to be 788shut down.</p> 789 790<p>To release an instance of the {@link android.hardware.Camera} object, use the {@link 791android.hardware.Camera#release() Camera.release()} method, as shown in the example code below.</p> 792 793<pre> 794public class CameraActivity extends Activity { 795 private Camera mCamera; 796 private SurfaceView mPreview; 797 private MediaRecorder mMediaRecorder; 798 799 ... 800 801 @Override 802 protected void onPause() { 803 super.onPause(); 804 releaseMediaRecorder(); // if you are using MediaRecorder, release it first 805 releaseCamera(); // release the camera immediately on pause event 806 } 807 808 private void releaseMediaRecorder(){ 809 if (mMediaRecorder != null) { 810 mMediaRecorder.reset(); // clear recorder configuration 811 mMediaRecorder.release(); // release the recorder object 812 mMediaRecorder = null; 813 mCamera.lock(); // lock camera for later use 814 } 815 } 816 817 private void releaseCamera(){ 818 if (mCamera != null){ 819 mCamera.release(); // release the camera for other applications 820 mCamera = null; 821 } 822 } 823} 824</pre> 825 826<p class="caution"><strong>Caution:</strong> If your application does not properly release the 827camera, all subsequent attempts to access the camera, including those by your own application, will 828fail and may cause your or other applications to be shut down.</p> 829 830 831<h2 id="saving-media">Saving Media Files</h2> 832<p>Media files created by users such as pictures and videos should be saved to a device's external 833storage directory (SD Card) to conserve system space and to allow users to access these files 834without their device. There are many possible directory locations to save media files on a device, 835however there are only two standard locations you should consider as a developer:</p> 836 837<ul> 838 <li><strong>{@link android.os.Environment#getExternalStoragePublicDirectory(java.lang.String) 839Environment.getExternalStoragePublicDirectory}({@link android.os.Environment#DIRECTORY_PICTURES 840Environment.DIRECTORY_PICTURES})</strong> - This method returns the standard, shared and recommended 841location for saving pictures and videos. This directory is shared (public), so other applications 842can easily discover, read, change and delete files saved in this location. If your application is 843uninstalled by the user, media files saved to this location will not be removed. To avoid 844interfering with users existing pictures and videos, you should create a sub-directory for your 845application's media files within this directory, as shown in the code sample below. This method is 846available in Android 2.2 (API Level 8), for equivalent calls in earlier API versions, see <a 847href="{@docRoot}guide/topics/data/data-storage.html#SavingSharedFiles">Saving Shared Files</a>.</li> 848 <li><strong>{@link android.content.Context#getExternalFilesDir(java.lang.String) 849Context.getExternalFilesDir}({@link android.os.Environment#DIRECTORY_PICTURES 850Environment.DIRECTORY_PICTURES})</strong> - This method returns a standard location for saving 851pictures and videos which are associated with your application. If your application is uninstalled, 852any files saved in this location are removed. Security is not enforced for files in this 853location and other applications may read, change and delete them.</li> 854</ul> 855 856<p>The following example code demonstrates how to create a {@link java.io.File} or {@link 857android.net.Uri} location for a media file that can be used when invoking a device's camera with 858an {@link android.content.Intent} or as part of a <a href="#custom-camera">Building a Camera 859App</a>.</p> 860 861<pre> 862public static final int MEDIA_TYPE_IMAGE = 1; 863public static final int MEDIA_TYPE_VIDEO = 2; 864 865/** Create a file Uri for saving an image or video */ 866private static Uri getOutputMediaFileUri(int type){ 867 return Uri.fromFile(getOutputMediaFile(type)); 868} 869 870/** Create a File for saving an image or video */ 871private static File getOutputMediaFile(int type){ 872 // To be safe, you should check that the SDCard is mounted 873 // using Environment.getExternalStorageState() before doing this. 874 875 File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory( 876 Environment.DIRECTORY_PICTURES), "MyCameraApp"); 877 // This location works best if you want the created images to be shared 878 // between applications and persist after your app has been uninstalled. 879 880 // Create the storage directory if it does not exist 881 if (! mediaStorageDir.exists()){ 882 if (! mediaStorageDir.mkdirs()){ 883 Log.d("MyCameraApp", "failed to create directory"); 884 return null; 885 } 886 } 887 888 // Create a media file name 889 String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 890 File mediaFile; 891 if (type == MEDIA_TYPE_IMAGE){ 892 mediaFile = new File(mediaStorageDir.getPath() + File.separator + 893 "IMG_"+ timeStamp + ".jpg"); 894 } else if(type == MEDIA_TYPE_VIDEO) { 895 mediaFile = new File(mediaStorageDir.getPath() + File.separator + 896 "VID_"+ timeStamp + ".mp4"); 897 } else { 898 return null; 899 } 900 901 return mediaFile; 902} 903</pre> 904 905<p class="note"><strong>Note:</strong> {@link 906android.os.Environment#getExternalStoragePublicDirectory(java.lang.String) 907Environment.getExternalStoragePublicDirectory()} is available in Android 2.2 (API Level 8) or 908higher. If you are targeting devices with earlier versions of Android, use {@link 909android.os.Environment#getExternalStorageDirectory() Environment.getExternalStorageDirectory()} 910instead. For more information, see <a 911href="{@docRoot}guide/topics/data/data-storage.html#SavingSharedFiles">Saving Shared Files</a>.</p> 912 913<p>For more information about saving files on an Android device, see <a 914href="{@docRoot}guide/topics/data/data-storage.html">Data Storage</a>.</p> 915 916 917<h2 id="camera-features">Camera Features</h2> 918<p>Android supports a wide array of camera features you can control with your camera application, 919such as picture format, flash mode, focus settings, and many more. This section lists the common 920camera features, and briefly discusses how to use them. Most camera features can be accessed and set 921using the through {@link android.hardware.Camera.Parameters} object. However, there are several 922important features that require more than simple settings in {@link 923android.hardware.Camera.Parameters}. These features are covered in the following sections:<p> 924 925<ul> 926 <li><a href="#metering-focus-areas">Metering and focus areas</a></li> 927 <li><a href="#face-detection">Face detection</a></li> 928 <li><a href="#time-lapse-video">Time lapse video</a></li> 929</ul> 930 931<p>For general information about how to use features that are controlled through {@link 932android.hardware.Camera.Parameters}, review the <a href="#using-features">Using camera 933features</a> section. For more detailed information about how to use features controlled through the 934camera parameters object, follow the links in the feature list below to the API reference 935documentation.</p> 936 937<p class="table-caption" id="table1"> 938 <strong>Table 1.</strong> Common camera features sorted by the Android API Level in which they 939were introduced.</p> 940<table> 941 <tr> 942 <th>Feature</th> <th>API Level</th> <th>Description</th> 943 </tr> 944 <tr> 945 <td><a href="#face-detection">Face Detection</a></td> 946 <td>14</td> 947 <td>Identify human faces within a picture and use them for focus, metering and white 948balance</td> 949 </tr> 950 <tr> 951 <td><a href="#metering-focus-areas">Metering Areas</a></td> 952 <td>14</td> 953 <td>Specify one or more areas within an image for calculating white balance</td> 954 </tr> 955 <tr> 956 <td><a href="#metering-focus-areas">Focus Areas</a></td> 957 <td>14</td> 958 <td>Set one or more areas within an image to use for focus</td> 959 </tr> 960 <tr> 961 <td>{@link android.hardware.Camera.Parameters#setAutoWhiteBalanceLock White Balance Lock}</td> 962 <td>14</td> 963 <td>Stop or start automatic white balance adjustments</td> 964 </tr> 965 <tr> 966 <td>{@link android.hardware.Camera.Parameters#setAutoExposureLock Exposure Lock}</td> 967 <td>14</td> 968 <td>Stop or start automatic exposure adjustments</td> 969 </tr> 970 <tr> 971 <td>{@link android.hardware.Camera#takePicture Video Snapshot}</td> 972 <td>14</td> 973 <td>Take a picture while shooting video (frame grab)</td> 974 </tr> 975 <tr> 976 <td><a href="#time-lapse-video">Time Lapse Video</a></td> 977 <td>11</td> 978 <td>Record frames with set delays to record a time lapse video</td> 979 </tr> 980 <tr> 981 <td>{@link android.hardware.Camera#open(int) Multiple Cameras}</td> 982 <td>9</td> 983 <td>Support for more than one camera on a device, including front-facing and back-facing 984cameras</td> 985 </tr> 986 <tr> 987 <td>{@link android.hardware.Camera.Parameters#getFocusDistances Focus Distance}</td> 988 <td>9</td> 989 <td>Reports distances between the camera and objects that appear to be in focus</td> 990 </tr> 991 <tr> 992 <td>{@link android.hardware.Camera.Parameters#setZoom Zoom}</td> 993 <td>8</td> 994 <td>Set image magnification</td> 995 </tr> 996 <tr> 997 <td>{@link android.hardware.Camera.Parameters#setExposureCompensation Exposure 998Compensation}</td> 999 <td>8</td> 1000 <td>Increase or decrease the light exposure level</td> 1001 </tr> 1002 <tr> 1003 <td>{@link android.hardware.Camera.Parameters#setGpsLatitude GPS Data}</td> 1004 <td>5</td> 1005 <td>Include or omit geographic location data with the image</td> 1006 </tr> 1007 <tr> 1008 <td>{@link android.hardware.Camera.Parameters#setWhiteBalance White Balance}</td> 1009 <td>5</td> 1010 <td>Set the white balance mode, which affects color values in the captured image</td> 1011 </tr> 1012 <tr> 1013 <td>{@link android.hardware.Camera.Parameters#setFocusMode Focus Mode}</td> 1014 <td>5</td> 1015 <td>Set how the camera focuses on a subject such as automatic, fixed, macro or infinity</td> 1016 </tr> 1017 <tr> 1018 <td>{@link android.hardware.Camera.Parameters#setSceneMode Scene Mode}</td> 1019 <td>5</td> 1020 <td>Apply a preset mode for specific types of photography situations such as night, beach, snow 1021or candlelight scenes</td> 1022 </tr> 1023 <tr> 1024 <td>{@link android.hardware.Camera.Parameters#setJpegQuality JPEG Quality}</td> 1025 <td>5</td> 1026 <td>Set the compression level for a JPEG image, which increases or decreases image output file 1027quality and size</td> 1028 </tr> 1029 <tr> 1030 <td>{@link android.hardware.Camera.Parameters#setFlashMode Flash Mode}</td> 1031 <td>5</td> 1032 <td>Turn flash on, off, or use automatic setting</td> 1033 </tr> 1034 <tr> 1035 <td>{@link android.hardware.Camera.Parameters#setColorEffect Color Effects}</td> 1036 <td>5</td> 1037 <td>Apply a color effect to the captured image such as black and white, sepia tone or negative. 1038</td> 1039 </tr> 1040 <tr> 1041 <td>{@link android.hardware.Camera.Parameters#setAntibanding Anti-Banding}</td> 1042 <td>5</td> 1043 <td>Reduces the effect of banding in color gradients due to JPEG compression</td> 1044 </tr> 1045 <tr> 1046 <td>{@link android.hardware.Camera.Parameters#setPictureFormat Picture Format}</td> 1047 <td>1</td> 1048 <td>Specify the file format for the picture</td> 1049 </tr> 1050 <tr> 1051 <td>{@link android.hardware.Camera.Parameters#setPictureSize Picture Size}</td> 1052 <td>1</td> 1053 <td>Specify the pixel dimensions of the saved picture</td> 1054 </tr> 1055</table> 1056 1057<p class="note"><strong>Note:</strong> These features are not supported on all devices due to 1058hardware differences and software implementation. For information on checking the availability 1059of features on the device where your application is running, see <a href="#check-feature">Checking 1060feature availability</a>.</p> 1061 1062 1063<h3 id="check-feature">Checking feature availability</h3> 1064<p>The first thing to understand when setting out to use camera features on Android devices is that 1065not all camera features are supported on all devices. In addition, devices that support a particular 1066feature may support them to different levels or with different options. Therefore, part of your 1067decision process as you develop a camera application is to decide what camera features you want to 1068support and to what level. After making that decision, you should plan on including code in your 1069camera application that checks to see if device hardware supports those features and fails 1070gracefully if a feature is not available.</p> 1071 1072<p>You can check the availabilty of camera features by getting an instance of a camera's parameters 1073object, and checking the relevant methods. The following code sample shows you how to obtain a 1074{@link android.hardware.Camera.Parameters} object and check if the camera supports the autofocus 1075feature:</p> 1076 1077<pre> 1078// get Camera parameters 1079Camera.Parameters params = mCamera.getParameters(); 1080 1081List<String> focusModes = params.getSupportedFocusModes(); 1082if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) { 1083 // Autofocus mode is supported 1084} 1085</pre> 1086 1087<p>You can use the technique shown above for most camera features. The 1088{@link android.hardware.Camera.Parameters} object provides a {@code getSupported...()}, {@code 1089is...Supported()} or {@code getMax...()} method to determine if (and to what extent) a feature is 1090supported.</p> 1091 1092<p>If your application requires certain camera features in order to function properly, you can 1093require them through additions to your application manifest. When you declare the use of specific 1094camera features, such as flash and auto-focus, Google Play restricts your application from 1095being installed on devices which do not support these features. For a list of camera features that 1096can be declared in your app manifest, see the manifest 1097<a href="{@docRoot}guide/topics/manifest/uses-feature-element.html#hw-features"> Features 1098Reference</a>.</p> 1099 1100<h3 id="using-features">Using camera features</h3> 1101<p>Most camera features are activated and controlled using a {@link 1102android.hardware.Camera.Parameters} object. You obtain this object by first getting an instance of 1103the {@link android.hardware.Camera} object, calling the {@link 1104android.hardware.Camera#getParameters getParameters()} method, changing the returned parameter 1105object and then setting it back into the camera object, as demonstrated in the following example 1106code:</p> 1107 1108<pre> 1109// get Camera parameters 1110Camera.Parameters params = mCamera.getParameters(); 1111// set the focus mode 1112params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); 1113// set Camera parameters 1114mCamera.setParameters(params); 1115</pre> 1116 1117<p>This technique works for nearly all camera features, and most parameters can be changed at any 1118time after you have obtained an instance of the {@link android.hardware.Camera} object. Changes to 1119parameters are typically visible to the user immediately in the application's camera preview. 1120On the software side, parameter changes may take several frames to actually take effect as the 1121camera hardware processes the new instructions and then sends updated image data.</p> 1122 1123<p class="caution"><strong>Important:</strong> Some camera features cannot be changed at will. In 1124particular, changing the size or orientation of the camera preview requires that you first stop the 1125preview, change the preview size, and then restart the preview. Starting with Android 4.0 (API 1126Level 14) preview orientation can be changed without restarting the preview.</p> 1127 1128<p>Other camera features require more code in order to implement, including:</p> 1129<ul> 1130 <li>Metering and focus areas</li> 1131 <li>Face detection</li> 1132 <li>Time lapse video</li> 1133</ul> 1134<p>A quick outline of how to implement these features is provided in the following sections.</p> 1135 1136 1137<h3 id="metering-focus-areas">Metering and focus areas</h3> 1138<p>In some photographic scenarios, automatic focusing and light metering may not produce the 1139desired results. Starting with Android 4.0 (API Level 14), your camera application can provide 1140additional controls to allow your app or users to specify areas in an image to use for determining 1141focus or light level settings and pass these values to the camera hardware for use in capturing 1142images or video.</p> 1143 1144<p>Areas for metering and focus work very similarly to other camera features, in that you control 1145them through methods in the {@link android.hardware.Camera.Parameters} object. The following code 1146demonstrates setting two light metering areas for an instance of 1147{@link android.hardware.Camera}:</p> 1148 1149<pre> 1150// Create an instance of Camera 1151mCamera = getCameraInstance(); 1152 1153// set Camera parameters 1154Camera.Parameters params = mCamera.getParameters(); 1155 1156if (params.getMaxNumMeteringAreas() > 0){ // check that metering areas are supported 1157 List<Camera.Area> meteringAreas = new ArrayList<Camera.Area>(); 1158 1159 Rect areaRect1 = new Rect(-100, -100, 100, 100); // specify an area in center of image 1160 meteringAreas.add(new Camera.Area(areaRect1, 600)); // set weight to 60% 1161 Rect areaRect2 = new Rect(800, -1000, 1000, -800); // specify an area in upper right of image 1162 meteringAreas.add(new Camera.Area(areaRect2, 400)); // set weight to 40% 1163 params.setMeteringAreas(meteringAreas); 1164} 1165 1166mCamera.setParameters(params); 1167</pre> 1168 1169<p>The {@link android.hardware.Camera.Area} object contains two data parameters: A {@link 1170android.graphics.Rect} object for specifying an area within the camera's field of view and a weight 1171value, which tells the camera what level of importance this area should be given in light metering 1172or focus calculations.</p> 1173 1174<p>The {@link android.graphics.Rect} field in a {@link android.hardware.Camera.Area} object 1175describes a rectangular shape mapped on a 2000 x 2000 unit grid. The coordinates -1000, -1000 1176represent the top, left corner of the camera image, and coordinates 1000, 1000 represent the 1177bottom, right corner of the camera image, as shown in the illustration below.</p> 1178 1179<img src='images/camera-area-coordinates.png' /> 1180<p class="img-caption"> 1181 <strong>Figure 1.</strong> The red lines illustrate the coordinate system for specifying a 1182{@link android.hardware.Camera.Area} within a camera preview. The blue box shows the location and 1183shape of an camera area with the {@link android.graphics.Rect} values 333,333,667,667. 1184</p> 1185 1186<p>The bounds of this coordinate system always correspond to the outer edge of the image visible in 1187the camera preview and do not shrink or expand with the zoom level. Similarly, rotation of the image 1188preview using {@link android.hardware.Camera#setDisplayOrientation Camera.setDisplayOrientation()} 1189does not remap the coordinate system.</p> 1190 1191 1192<h3 id="face-detection">Face detection</h3> 1193<p>For pictures that include people, faces are usually the most important part of the picture, and 1194should be used for determining both focus and white balance when capturing an image. The Android 4.0 1195(API Level 14) framework provides APIs for identifying faces and calculating picture settings using 1196face recognition technology.</p> 1197 1198<p class="note"><strong>Note:</strong> While the face detection feature is running, 1199{@link android.hardware.Camera.Parameters#setWhiteBalance}, 1200{@link android.hardware.Camera.Parameters#setFocusAreas} and 1201{@link android.hardware.Camera.Parameters#setMeteringAreas} have no effect.</p> 1202 1203<p>Using the face detection feature in your camera application requires a few general steps:</p> 1204<ul> 1205 <li>Check that face detection is supported on the device</li> 1206 <li>Create a face detection listener</li> 1207 <li>Add the face detection listener to your camera object</li> 1208 <li>Start face detection after preview (and after <em>every</em> preview restart)</li> 1209</ul> 1210 1211<p>The face detection feature is not supported on all devices. You can check that this feature is 1212supported by calling {@link android.hardware.Camera.Parameters#getMaxNumDetectedFaces}. An 1213example of this check is shown in the {@code startFaceDetection()} sample method below.</p> 1214 1215<p>In order to be notified and respond to the detection of a face, your camera application must set 1216a listener for face detection events. In order to do this, you must create a listener class that 1217implements the {@link android.hardware.Camera.FaceDetectionListener} interface as shown in the 1218example code below.</p> 1219 1220<pre> 1221class MyFaceDetectionListener implements Camera.FaceDetectionListener { 1222 1223 @Override 1224 public void onFaceDetection(Face[] faces, Camera camera) { 1225 if (faces.length > 0){ 1226 Log.d("FaceDetection", "face detected: "+ faces.length + 1227 " Face 1 Location X: " + faces[0].rect.centerX() + 1228 "Y: " + faces[0].rect.centerY() ); 1229 } 1230 } 1231} 1232</pre> 1233 1234<p>After creating this class, you then set it into your application's 1235{@link android.hardware.Camera} object, as shown in the example code below:</p> 1236 1237<pre> 1238mCamera.setFaceDetectionListener(new MyFaceDetectionListener()); 1239</pre> 1240 1241<p>Your application must start the face detection function each time you start (or restart) the 1242camera preview. Create a method for starting face detection so you can call it as needed, as shown 1243in the example code below.</p> 1244 1245<pre> 1246public void startFaceDetection(){ 1247 // Try starting Face Detection 1248 Camera.Parameters params = mCamera.getParameters(); 1249 1250 // start face detection only *after* preview has started 1251 if (params.getMaxNumDetectedFaces() > 0){ 1252 // camera supports face detection, so can start it: 1253 mCamera.startFaceDetection(); 1254 } 1255} 1256</pre> 1257 1258<p>You must start face detection <em>each time</em> you start (or restart) the camera preview. If 1259you use the preview class shown in <a href="#camera-preview">Creating a preview class</a>, add your 1260{@link android.hardware.Camera#startFaceDetection startFaceDetection()} method to both the 1261{@link android.view.SurfaceHolder.Callback#surfaceCreated surfaceCreated()} and {@link 1262android.view.SurfaceHolder.Callback#surfaceChanged surfaceChanged()} methods in your preview class, 1263as shown in the sample code below.</p> 1264 1265<pre> 1266public void surfaceCreated(SurfaceHolder holder) { 1267 try { 1268 mCamera.setPreviewDisplay(holder); 1269 mCamera.startPreview(); 1270 1271 startFaceDetection(); // start face detection feature 1272 1273 } catch (IOException e) { 1274 Log.d(TAG, "Error setting camera preview: " + e.getMessage()); 1275 } 1276} 1277 1278public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { 1279 1280 if (mHolder.getSurface() == null){ 1281 // preview surface does not exist 1282 Log.d(TAG, "mHolder.getSurface() == null"); 1283 return; 1284 } 1285 1286 try { 1287 mCamera.stopPreview(); 1288 1289 } catch (Exception e){ 1290 // ignore: tried to stop a non-existent preview 1291 Log.d(TAG, "Error stopping camera preview: " + e.getMessage()); 1292 } 1293 1294 try { 1295 mCamera.setPreviewDisplay(mHolder); 1296 mCamera.startPreview(); 1297 1298 startFaceDetection(); // re-start face detection feature 1299 1300 } catch (Exception e){ 1301 // ignore: tried to stop a non-existent preview 1302 Log.d(TAG, "Error starting camera preview: " + e.getMessage()); 1303 } 1304} 1305</pre> 1306 1307<p class="note"><strong>Note:</strong> Remember to call this method <em>after</em> calling 1308{@link android.hardware.Camera#startPreview startPreview()}. Do not attempt to start face detection 1309in the {@link android.app.Activity#onCreate onCreate()} method of your camera app's main activity, 1310as the preview is not available by this point in your application's the execution.</p> 1311 1312 1313<h3 id="time-lapse-video">Time lapse video</h3> 1314<p>Time lapse video allows users to create video clips that combine pictures taken a few seconds or 1315minutes apart. This feature uses {@link android.media.MediaRecorder} to record the images for a time 1316lapse sequence. </p> 1317 1318<p>To record a time lapse video with {@link android.media.MediaRecorder}, you must configure the 1319recorder object as if you are recording a normal video, setting the captured frames per second to a 1320low number and using one of the time lapse quality settings, as shown in the code example below.</p> 1321 1322<pre> 1323// Step 3: Set a CamcorderProfile (requires API Level 8 or higher) 1324mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_TIME_LAPSE_HIGH)); 1325... 1326// Step 5.5: Set the video capture rate to a low number 1327mMediaRecorder.setCaptureRate(0.1); // capture a frame every 10 seconds 1328</pre> 1329 1330<p>These settings must be done as part of a larger configuration procedure for {@link 1331android.media.MediaRecorder}. For a full configuration code example, see <a 1332href="#configuring-mediarecorder">Configuring MediaRecorder</a>. Once the configuration is complete, 1333you start the video recording as if you were recording a normal video clip. For more information 1334about configuring and running {@link android.media.MediaRecorder}, see <a 1335href="#capture-video">Capturing videos</a>.</p> 1336