Camera.java revision e309a0fd2e528039b3c1f1372a9a7095bcd852cc
1/* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.hardware; 18 19import java.lang.ref.WeakReference; 20import java.util.ArrayList; 21import java.util.HashMap; 22import java.util.List; 23import java.util.StringTokenizer; 24import java.io.IOException; 25 26import android.util.Log; 27import android.view.Surface; 28import android.view.SurfaceHolder; 29import android.graphics.ImageFormat; 30import android.graphics.SurfaceTexture; 31import android.os.Handler; 32import android.os.Looper; 33import android.os.Message; 34 35/** 36 * The Camera class is used to set image capture settings, start/stop preview, 37 * snap pictures, and retrieve frames for encoding for video. This class is a 38 * client for the Camera service, which manages the actual camera hardware. 39 * 40 * <p>To access the device camera, you must declare the 41 * {@link android.Manifest.permission#CAMERA} permission in your Android 42 * Manifest. Also be sure to include the 43 * <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html"><uses-feature></a> 44 * manifest element to declare camera features used by your application. 45 * For example, if you use the camera and auto-focus feature, your Manifest 46 * should include the following:</p> 47 * <pre> <uses-permission android:name="android.permission.CAMERA" /> 48 * <uses-feature android:name="android.hardware.camera" /> 49 * <uses-feature android:name="android.hardware.camera.autofocus" /></pre> 50 * 51 * <p>To take pictures with this class, use the following steps:</p> 52 * 53 * <ol> 54 * <li>Obtain an instance of Camera from {@link #open(int)}. 55 * 56 * <li>Get existing (default) settings with {@link #getParameters()}. 57 * 58 * <li>If necessary, modify the returned {@link Camera.Parameters} object and call 59 * {@link #setParameters(Camera.Parameters)}. 60 * 61 * <li>If desired, call {@link #setDisplayOrientation(int)}. 62 * 63 * <li><b>Important</b>: Pass a fully initialized {@link SurfaceHolder} to 64 * {@link #setPreviewDisplay(SurfaceHolder)}. Without a surface, the camera 65 * will be unable to start the preview. 66 * 67 * <li><b>Important</b>: Call {@link #startPreview()} to start updating the 68 * preview surface. Preview must be started before you can take a picture. 69 * 70 * <li>When you want, call {@link #takePicture(Camera.ShutterCallback, 71 * Camera.PictureCallback, Camera.PictureCallback, Camera.PictureCallback)} to 72 * capture a photo. Wait for the callbacks to provide the actual image data. 73 * 74 * <li>After taking a picture, preview display will have stopped. To take more 75 * photos, call {@link #startPreview()} again first. 76 * 77 * <li>Call {@link #stopPreview()} to stop updating the preview surface. 78 * 79 * <li><b>Important:</b> Call {@link #release()} to release the camera for 80 * use by other applications. Applications should release the camera 81 * immediately in {@link android.app.Activity#onPause()} (and re-{@link #open()} 82 * it in {@link android.app.Activity#onResume()}). 83 * </ol> 84 * 85 * <p>To quickly switch to video recording mode, use these steps:</p> 86 * 87 * <ol> 88 * <li>Obtain and initialize a Camera and start preview as described above. 89 * 90 * <li>Call {@link #unlock()} to allow the media process to access the camera. 91 * 92 * <li>Pass the camera to {@link android.media.MediaRecorder#setCamera(Camera)}. 93 * See {@link android.media.MediaRecorder} information about video recording. 94 * 95 * <li>When finished recording, call {@link #reconnect()} to re-acquire 96 * and re-lock the camera. 97 * 98 * <li>If desired, restart preview and take more photos or videos. 99 * 100 * <li>Call {@link #stopPreview()} and {@link #release()} as described above. 101 * </ol> 102 * 103 * <p>This class is not thread-safe, and is meant for use from one event thread. 104 * Most long-running operations (preview, focus, photo capture, etc) happen 105 * asynchronously and invoke callbacks as necessary. Callbacks will be invoked 106 * on the event thread {@link #open(int)} was called from. This class's methods 107 * must never be called from multiple threads at once.</p> 108 * 109 * <p class="caution"><strong>Caution:</strong> Different Android-powered devices 110 * may have different hardware specifications, such as megapixel ratings and 111 * auto-focus capabilities. In order for your application to be compatible with 112 * more devices, you should not make assumptions about the device camera 113 * specifications.</p> 114 */ 115public class Camera { 116 private static final String TAG = "Camera"; 117 118 // These match the enums in frameworks/base/include/camera/Camera.h 119 private static final int CAMERA_MSG_ERROR = 0x001; 120 private static final int CAMERA_MSG_SHUTTER = 0x002; 121 private static final int CAMERA_MSG_FOCUS = 0x004; 122 private static final int CAMERA_MSG_ZOOM = 0x008; 123 private static final int CAMERA_MSG_PREVIEW_FRAME = 0x010; 124 private static final int CAMERA_MSG_VIDEO_FRAME = 0x020; 125 private static final int CAMERA_MSG_POSTVIEW_FRAME = 0x040; 126 private static final int CAMERA_MSG_RAW_IMAGE = 0x080; 127 private static final int CAMERA_MSG_COMPRESSED_IMAGE = 0x100; 128 private static final int CAMERA_MSG_ALL_MSGS = 0x1FF; 129 130 private int mNativeContext; // accessed by native methods 131 private EventHandler mEventHandler; 132 private ShutterCallback mShutterCallback; 133 private PictureCallback mRawImageCallback; 134 private PictureCallback mJpegCallback; 135 private PreviewCallback mPreviewCallback; 136 private PictureCallback mPostviewCallback; 137 private AutoFocusCallback mAutoFocusCallback; 138 private OnZoomChangeListener mZoomListener; 139 private ErrorCallback mErrorCallback; 140 private boolean mOneShot; 141 private boolean mWithBuffer; 142 143 /** 144 * Returns the number of physical cameras available on this device. 145 */ 146 public native static int getNumberOfCameras(); 147 148 /** 149 * Returns the information about a particular camera. 150 * If {@link #getNumberOfCameras()} returns N, the valid id is 0 to N-1. 151 */ 152 public native static void getCameraInfo(int cameraId, CameraInfo cameraInfo); 153 154 /** 155 * Information about a camera 156 */ 157 public static class CameraInfo { 158 /** 159 * The facing of the camera is opposite to that of the screen. 160 */ 161 public static final int CAMERA_FACING_BACK = 0; 162 163 /** 164 * The facing of the camera is the same as that of the screen. 165 */ 166 public static final int CAMERA_FACING_FRONT = 1; 167 168 /** 169 * The direction that the camera faces to. It should be 170 * CAMERA_FACING_BACK or CAMERA_FACING_FRONT. 171 */ 172 public int facing; 173 174 /** 175 * The orientation of the camera image. The value is the angle that the 176 * camera image needs to be rotated clockwise so it shows correctly on 177 * the display in its natural orientation. It should be 0, 90, 180, or 270. 178 * 179 * For example, suppose a device has a naturally tall screen. The 180 * back-facing camera sensor is mounted in landscape. You are looking at 181 * the screen. If the top side of the camera sensor is aligned with the 182 * right edge of the screen in natural orientation, the value should be 183 * 90. If the top side of a front-facing camera sensor is aligned with 184 * the right of the screen, the value should be 270. 185 * 186 * @see #setDisplayOrientation(int) 187 * @see Parameters#setRotation(int) 188 * @see Parameters#setPreviewSize(int, int) 189 * @see Parameters#setPictureSize(int, int) 190 * @see Parameters#setJpegThumbnailSize(int, int) 191 */ 192 public int orientation; 193 }; 194 195 /** 196 * Creates a new Camera object to access a particular hardware camera. 197 * 198 * <p>You must call {@link #release()} when you are done using the camera, 199 * otherwise it will remain locked and be unavailable to other applications. 200 * 201 * <p>Your application should only have one Camera object active at a time 202 * for a particular hardware camera. 203 * 204 * <p>Callbacks from other methods are delivered to the event loop of the 205 * thread which called open(). If this thread has no event loop, then 206 * callbacks are delivered to the main application event loop. If there 207 * is no main application event loop, callbacks are not delivered. 208 * 209 * <p class="caution"><b>Caution:</b> On some devices, this method may 210 * take a long time to complete. It is best to call this method from a 211 * worker thread (possibly using {@link android.os.AsyncTask}) to avoid 212 * blocking the main application UI thread. 213 * 214 * @param cameraId the hardware camera to access, between 0 and 215 * {@link #getNumberOfCameras()}-1. 216 * @return a new Camera object, connected, locked and ready for use. 217 * @throws RuntimeException if connection to the camera service fails (for 218 * example, if the camera is in use by another process). 219 */ 220 public static Camera open(int cameraId) { 221 return new Camera(cameraId); 222 } 223 224 /** 225 * Creates a new Camera object to access the first back-facing camera on the 226 * device. If the device does not have a back-facing camera, this returns 227 * null. 228 * @see #open(int) 229 */ 230 public static Camera open() { 231 int numberOfCameras = getNumberOfCameras(); 232 CameraInfo cameraInfo = new CameraInfo(); 233 for (int i = 0; i < numberOfCameras; i++) { 234 getCameraInfo(i, cameraInfo); 235 if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) { 236 return new Camera(i); 237 } 238 } 239 return null; 240 } 241 242 Camera(int cameraId) { 243 mShutterCallback = null; 244 mRawImageCallback = null; 245 mJpegCallback = null; 246 mPreviewCallback = null; 247 mPostviewCallback = null; 248 mZoomListener = null; 249 250 Looper looper; 251 if ((looper = Looper.myLooper()) != null) { 252 mEventHandler = new EventHandler(this, looper); 253 } else if ((looper = Looper.getMainLooper()) != null) { 254 mEventHandler = new EventHandler(this, looper); 255 } else { 256 mEventHandler = null; 257 } 258 259 native_setup(new WeakReference<Camera>(this), cameraId); 260 } 261 262 protected void finalize() { 263 native_release(); 264 } 265 266 private native final void native_setup(Object camera_this, int cameraId); 267 private native final void native_release(); 268 269 270 /** 271 * Disconnects and releases the Camera object resources. 272 * 273 * <p>You must call this as soon as you're done with the Camera object.</p> 274 */ 275 public final void release() { 276 native_release(); 277 } 278 279 /** 280 * Unlocks the camera to allow another process to access it. 281 * Normally, the camera is locked to the process with an active Camera 282 * object until {@link #release()} is called. To allow rapid handoff 283 * between processes, you can call this method to release the camera 284 * temporarily for another process to use; once the other process is done 285 * you can call {@link #reconnect()} to reclaim the camera. 286 * 287 * <p>This must be done before calling 288 * {@link android.media.MediaRecorder#setCamera(Camera)}. 289 * 290 * <p>If you are not recording video, you probably do not need this method. 291 * 292 * @throws RuntimeException if the camera cannot be unlocked. 293 */ 294 public native final void unlock(); 295 296 /** 297 * Re-locks the camera to prevent other processes from accessing it. 298 * Camera objects are locked by default unless {@link #unlock()} is 299 * called. Normally {@link #reconnect()} is used instead. 300 * 301 * <p>If you are not recording video, you probably do not need this method. 302 * 303 * @throws RuntimeException if the camera cannot be re-locked (for 304 * example, if the camera is still in use by another process). 305 */ 306 public native final void lock(); 307 308 /** 309 * Reconnects to the camera service after another process used it. 310 * After {@link #unlock()} is called, another process may use the 311 * camera; when the process is done, you must reconnect to the camera, 312 * which will re-acquire the lock and allow you to continue using the 313 * camera. 314 * 315 * <p>This must be done after {@link android.media.MediaRecorder} is 316 * done recording if {@link android.media.MediaRecorder#setCamera(Camera)} 317 * was used. 318 * 319 * <p>If you are not recording video, you probably do not need this method. 320 * 321 * @throws IOException if a connection cannot be re-established (for 322 * example, if the camera is still in use by another process). 323 */ 324 public native final void reconnect() throws IOException; 325 326 /** 327 * Sets the {@link Surface} to be used for live preview. 328 * Either a surface or surface texture is necessary for preview, and 329 * preview is necessary to take pictures. The same surface can be re-set 330 * without harm. Setting a preview surface will un-set any preview surface 331 * texture that was set via {@link #setPreviewTexture}. 332 * 333 * <p>The {@link SurfaceHolder} must already contain a surface when this 334 * method is called. If you are using {@link android.view.SurfaceView}, 335 * you will need to register a {@link SurfaceHolder.Callback} with 336 * {@link SurfaceHolder#addCallback(SurfaceHolder.Callback)} and wait for 337 * {@link SurfaceHolder.Callback#surfaceCreated(SurfaceHolder)} before 338 * calling setPreviewDisplay() or starting preview. 339 * 340 * <p>This method must be called before {@link #startPreview()}. The 341 * one exception is that if the preview surface is not set (or set to null) 342 * before startPreview() is called, then this method may be called once 343 * with a non-null parameter to set the preview surface. (This allows 344 * camera setup and surface creation to happen in parallel, saving time.) 345 * The preview surface may not otherwise change while preview is running. 346 * 347 * @param holder containing the Surface on which to place the preview, 348 * or null to remove the preview surface 349 * @throws IOException if the method fails (for example, if the surface 350 * is unavailable or unsuitable). 351 */ 352 public final void setPreviewDisplay(SurfaceHolder holder) throws IOException { 353 if (holder != null) { 354 setPreviewDisplay(holder.getSurface()); 355 } else { 356 setPreviewDisplay((Surface)null); 357 } 358 } 359 360 private native final void setPreviewDisplay(Surface surface) throws IOException; 361 362 /** 363 * Sets the {@link SurfaceTexture} to be used for live preview. 364 * Either a surface or surface texture is necessary for preview, and 365 * preview is necessary to take pictures. The same surface texture can be 366 * re-set without harm. Setting a preview surface texture will un-set any 367 * preview surface that was set via {@link #setPreviewDisplay}. 368 * 369 * <p>This method must be called before {@link #startPreview()}. The 370 * one exception is that if the preview surface texture is not set (or set 371 * to null) before startPreview() is called, then this method may be called 372 * once with a non-null parameter to set the preview surface. (This allows 373 * camera setup and surface creation to happen in parallel, saving time.) 374 * The preview surface texture may not otherwise change while preview is 375 * running. 376 * 377 * The timestamps provided by {@link SurfaceTexture#getTimestamp()} for a 378 * SurfaceTexture set as the preview texture have an unspecified zero point, 379 * and cannot be directly compared between different cameras or different 380 * instances of the same camera, or across multiple runs of the same 381 * program. 382 * 383 * @param surfaceTexture the {@link SurfaceTexture} to which the preview 384 * images are to be sent or null to remove the current preview surface 385 * texture 386 * @throws IOException if the method fails (for example, if the surface 387 * texture is unavailable or unsuitable). 388 */ 389 public native final void setPreviewTexture(SurfaceTexture surfaceTexture) throws IOException; 390 391 /** 392 * Callback interface used to deliver copies of preview frames as 393 * they are displayed. 394 * 395 * @see #setPreviewCallback(Camera.PreviewCallback) 396 * @see #setOneShotPreviewCallback(Camera.PreviewCallback) 397 * @see #setPreviewCallbackWithBuffer(Camera.PreviewCallback) 398 * @see #startPreview() 399 */ 400 public interface PreviewCallback 401 { 402 /** 403 * Called as preview frames are displayed. This callback is invoked 404 * on the event thread {@link #open(int)} was called from. 405 * 406 * @param data the contents of the preview frame in the format defined 407 * by {@link android.graphics.ImageFormat}, which can be queried 408 * with {@link android.hardware.Camera.Parameters#getPreviewFormat()}. 409 * If {@link android.hardware.Camera.Parameters#setPreviewFormat(int)} 410 * is never called, the default will be the YCbCr_420_SP 411 * (NV21) format. 412 * @param camera the Camera service object. 413 */ 414 void onPreviewFrame(byte[] data, Camera camera); 415 }; 416 417 /** 418 * Starts capturing and drawing preview frames to the screen. 419 * Preview will not actually start until a surface is supplied 420 * with {@link #setPreviewDisplay(SurfaceHolder)} or 421 * {@link #setPreviewTexture(SurfaceTexture)}. 422 * 423 * <p>If {@link #setPreviewCallback(Camera.PreviewCallback)}, 424 * {@link #setOneShotPreviewCallback(Camera.PreviewCallback)}, or 425 * {@link #setPreviewCallbackWithBuffer(Camera.PreviewCallback)} were 426 * called, {@link Camera.PreviewCallback#onPreviewFrame(byte[], Camera)} 427 * will be called when preview data becomes available. 428 */ 429 public native final void startPreview(); 430 431 /** 432 * Stops capturing and drawing preview frames to the surface, and 433 * resets the camera for a future call to {@link #startPreview()}. 434 */ 435 public native final void stopPreview(); 436 437 /** 438 * Return current preview state. 439 * 440 * FIXME: Unhide before release 441 * @hide 442 */ 443 public native final boolean previewEnabled(); 444 445 /** 446 * Installs a callback to be invoked for every preview frame in addition 447 * to displaying them on the screen. The callback will be repeatedly called 448 * for as long as preview is active. This method can be called at any time, 449 * even while preview is live. Any other preview callbacks are overridden. 450 * 451 * @param cb a callback object that receives a copy of each preview frame, 452 * or null to stop receiving callbacks. 453 */ 454 public final void setPreviewCallback(PreviewCallback cb) { 455 mPreviewCallback = cb; 456 mOneShot = false; 457 mWithBuffer = false; 458 // Always use one-shot mode. We fake camera preview mode by 459 // doing one-shot preview continuously. 460 setHasPreviewCallback(cb != null, false); 461 } 462 463 /** 464 * Installs a callback to be invoked for the next preview frame in addition 465 * to displaying it on the screen. After one invocation, the callback is 466 * cleared. This method can be called any time, even when preview is live. 467 * Any other preview callbacks are overridden. 468 * 469 * @param cb a callback object that receives a copy of the next preview frame, 470 * or null to stop receiving callbacks. 471 */ 472 public final void setOneShotPreviewCallback(PreviewCallback cb) { 473 mPreviewCallback = cb; 474 mOneShot = true; 475 mWithBuffer = false; 476 setHasPreviewCallback(cb != null, false); 477 } 478 479 private native final void setHasPreviewCallback(boolean installed, boolean manualBuffer); 480 481 /** 482 * Installs a callback to be invoked for every preview frame, using buffers 483 * supplied with {@link #addCallbackBuffer(byte[])}, in addition to 484 * displaying them on the screen. The callback will be repeatedly called 485 * for as long as preview is active and buffers are available. 486 * Any other preview callbacks are overridden. 487 * 488 * <p>The purpose of this method is to improve preview efficiency and frame 489 * rate by allowing preview frame memory reuse. You must call 490 * {@link #addCallbackBuffer(byte[])} at some point -- before or after 491 * calling this method -- or no callbacks will received. 492 * 493 * The buffer queue will be cleared if this method is called with a null 494 * callback, {@link #setPreviewCallback(Camera.PreviewCallback)} is called, 495 * or {@link #setOneShotPreviewCallback(Camera.PreviewCallback)} is called. 496 * 497 * @param cb a callback object that receives a copy of the preview frame, 498 * or null to stop receiving callbacks and clear the buffer queue. 499 * @see #addCallbackBuffer(byte[]) 500 */ 501 public final void setPreviewCallbackWithBuffer(PreviewCallback cb) { 502 mPreviewCallback = cb; 503 mOneShot = false; 504 mWithBuffer = true; 505 setHasPreviewCallback(cb != null, true); 506 } 507 508 /** 509 * Adds a pre-allocated buffer to the preview callback buffer queue. 510 * Applications can add one or more buffers to the queue. When a preview 511 * frame arrives and there is still at least one available buffer, the 512 * buffer will be used and removed from the queue. Then preview callback is 513 * invoked with the buffer. If a frame arrives and there is no buffer left, 514 * the frame is discarded. Applications should add buffers back when they 515 * finish processing the data in them. 516 * 517 * <p>The size of the buffer is determined by multiplying the preview 518 * image width, height, and bytes per pixel. The width and height can be 519 * read from {@link Camera.Parameters#getPreviewSize()}. Bytes per pixel 520 * can be computed from 521 * {@link android.graphics.ImageFormat#getBitsPerPixel(int)} / 8, 522 * using the image format from {@link Camera.Parameters#getPreviewFormat()}. 523 * 524 * <p>This method is only necessary when 525 * {@link #setPreviewCallbackWithBuffer(PreviewCallback)} is used. When 526 * {@link #setPreviewCallback(PreviewCallback)} or 527 * {@link #setOneShotPreviewCallback(PreviewCallback)} are used, buffers 528 * are automatically allocated. When a supplied buffer is too small to 529 * hold the preview frame data, preview callback will return null and 530 * the buffer will be removed from the buffer queue. 531 * 532 * @param callbackBuffer the buffer to add to the queue. 533 * The size should be width * height * bits_per_pixel / 8. 534 * @see #setPreviewCallbackWithBuffer(PreviewCallback) 535 */ 536 public final void addCallbackBuffer(byte[] callbackBuffer) 537 { 538 _addCallbackBuffer(callbackBuffer, CAMERA_MSG_PREVIEW_FRAME); 539 } 540 541 /** 542 * Adds a pre-allocated buffer to the raw image callback buffer queue. 543 * Applications can add one or more buffers to the queue. When a raw image 544 * frame arrives and there is still at least one available buffer, the 545 * buffer will be used to hold the raw image data and removed from the 546 * queue. Then raw image callback is invoked with the buffer. If a raw 547 * image frame arrives but there is no buffer left, the frame is 548 * discarded. Applications should add buffers back when they finish 549 * processing the data in them by calling this method again in order 550 * to avoid running out of raw image callback buffers. 551 * 552 * <p>The size of the buffer is determined by multiplying the raw image 553 * width, height, and bytes per pixel. The width and height can be 554 * read from {@link Camera.Parameters#getPictureSize()}. Bytes per pixel 555 * can be computed from 556 * {@link android.graphics.ImageFormat#getBitsPerPixel(int)} / 8, 557 * using the image format from {@link Camera.Parameters#getPreviewFormat()}. 558 * 559 * <p>This method is only necessary when the PictureCallbck for raw image 560 * is used while calling {@link #takePicture(Camera.ShutterCallback, 561 * Camera.PictureCallback, Camera.PictureCallback, Camera.PictureCallback)}. 562 * 563 * Please note that by calling this method, the mode for application-managed 564 * callback buffers is triggered. If this method has never been called, 565 * null will be returned by the raw image callback since there is 566 * no image callback buffer available. Furthermore, When a supplied buffer 567 * is too small to hold the raw image data, raw image callback will return 568 * null and the buffer will be removed from the buffer queue. 569 * 570 * @param callbackBuffer the buffer to add to the raw image callback buffer 571 * queue. The size should be width * height * (bits per pixel) / 8. An 572 * null callbackBuffer will be ignored and won't be added to the queue. 573 * 574 * @see #takePicture(Camera.ShutterCallback, 575 * Camera.PictureCallback, Camera.PictureCallback, Camera.PictureCallback)}. 576 * 577 * {@hide} 578 */ 579 public final void addRawImageCallbackBuffer(byte[] callbackBuffer) 580 { 581 addCallbackBuffer(callbackBuffer, CAMERA_MSG_RAW_IMAGE); 582 } 583 584 private final void addCallbackBuffer(byte[] callbackBuffer, int msgType) 585 { 586 // CAMERA_MSG_VIDEO_FRAME may be allowed in the future. 587 if (msgType != CAMERA_MSG_PREVIEW_FRAME && 588 msgType != CAMERA_MSG_RAW_IMAGE) { 589 throw new IllegalArgumentException( 590 "Unsupported message type: " + msgType); 591 } 592 593 _addCallbackBuffer(callbackBuffer, msgType); 594 } 595 596 private native final void _addCallbackBuffer( 597 byte[] callbackBuffer, int msgType); 598 599 private class EventHandler extends Handler 600 { 601 private Camera mCamera; 602 603 public EventHandler(Camera c, Looper looper) { 604 super(looper); 605 mCamera = c; 606 } 607 608 @Override 609 public void handleMessage(Message msg) { 610 switch(msg.what) { 611 case CAMERA_MSG_SHUTTER: 612 if (mShutterCallback != null) { 613 mShutterCallback.onShutter(); 614 } 615 return; 616 617 case CAMERA_MSG_RAW_IMAGE: 618 if (mRawImageCallback != null) { 619 mRawImageCallback.onPictureTaken((byte[])msg.obj, mCamera); 620 } 621 return; 622 623 case CAMERA_MSG_COMPRESSED_IMAGE: 624 if (mJpegCallback != null) { 625 mJpegCallback.onPictureTaken((byte[])msg.obj, mCamera); 626 } 627 return; 628 629 case CAMERA_MSG_PREVIEW_FRAME: 630 if (mPreviewCallback != null) { 631 PreviewCallback cb = mPreviewCallback; 632 if (mOneShot) { 633 // Clear the callback variable before the callback 634 // in case the app calls setPreviewCallback from 635 // the callback function 636 mPreviewCallback = null; 637 } else if (!mWithBuffer) { 638 // We're faking the camera preview mode to prevent 639 // the app from being flooded with preview frames. 640 // Set to oneshot mode again. 641 setHasPreviewCallback(true, false); 642 } 643 cb.onPreviewFrame((byte[])msg.obj, mCamera); 644 } 645 return; 646 647 case CAMERA_MSG_POSTVIEW_FRAME: 648 if (mPostviewCallback != null) { 649 mPostviewCallback.onPictureTaken((byte[])msg.obj, mCamera); 650 } 651 return; 652 653 case CAMERA_MSG_FOCUS: 654 if (mAutoFocusCallback != null) { 655 mAutoFocusCallback.onAutoFocus(msg.arg1 == 0 ? false : true, mCamera); 656 } 657 return; 658 659 case CAMERA_MSG_ZOOM: 660 if (mZoomListener != null) { 661 mZoomListener.onZoomChange(msg.arg1, msg.arg2 != 0, mCamera); 662 } 663 return; 664 665 case CAMERA_MSG_ERROR : 666 Log.e(TAG, "Error " + msg.arg1); 667 if (mErrorCallback != null) { 668 mErrorCallback.onError(msg.arg1, mCamera); 669 } 670 return; 671 672 default: 673 Log.e(TAG, "Unknown message type " + msg.what); 674 return; 675 } 676 } 677 } 678 679 private static void postEventFromNative(Object camera_ref, 680 int what, int arg1, int arg2, Object obj) 681 { 682 Camera c = (Camera)((WeakReference)camera_ref).get(); 683 if (c == null) 684 return; 685 686 if (c.mEventHandler != null) { 687 Message m = c.mEventHandler.obtainMessage(what, arg1, arg2, obj); 688 c.mEventHandler.sendMessage(m); 689 } 690 } 691 692 /** 693 * Callback interface used to notify on completion of camera auto focus. 694 * 695 * <p>Devices that do not support auto-focus will receive a "fake" 696 * callback to this interface. If your application needs auto-focus and 697 * should not be installed on devices <em>without</em> auto-focus, you must 698 * declare that your app uses the 699 * {@code android.hardware.camera.autofocus} feature, in the 700 * <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html"><uses-feature></a> 701 * manifest element.</p> 702 * 703 * @see #autoFocus(AutoFocusCallback) 704 */ 705 public interface AutoFocusCallback 706 { 707 /** 708 * Called when the camera auto focus completes. If the camera 709 * does not support auto-focus and autoFocus is called, 710 * onAutoFocus will be called immediately with a fake value of 711 * <code>success</code> set to <code>true</code>. 712 * 713 * @param success true if focus was successful, false if otherwise 714 * @param camera the Camera service object 715 */ 716 void onAutoFocus(boolean success, Camera camera); 717 }; 718 719 /** 720 * Starts camera auto-focus and registers a callback function to run when 721 * the camera is focused. This method is only valid when preview is active 722 * (between {@link #startPreview()} and before {@link #stopPreview()}). 723 * 724 * <p>Callers should check 725 * {@link android.hardware.Camera.Parameters#getFocusMode()} to determine if 726 * this method should be called. If the camera does not support auto-focus, 727 * it is a no-op and {@link AutoFocusCallback#onAutoFocus(boolean, Camera)} 728 * callback will be called immediately. 729 * 730 * <p>If your application should not be installed 731 * on devices without auto-focus, you must declare that your application 732 * uses auto-focus with the 733 * <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html"><uses-feature></a> 734 * manifest element.</p> 735 * 736 * <p>If the current flash mode is not 737 * {@link android.hardware.Camera.Parameters#FLASH_MODE_OFF}, flash may be 738 * fired during auto-focus, depending on the driver and camera hardware.<p> 739 * 740 * @param cb the callback to run 741 * @see #cancelAutoFocus() 742 */ 743 public final void autoFocus(AutoFocusCallback cb) 744 { 745 mAutoFocusCallback = cb; 746 native_autoFocus(); 747 } 748 private native final void native_autoFocus(); 749 750 /** 751 * Cancels any auto-focus function in progress. 752 * Whether or not auto-focus is currently in progress, 753 * this function will return the focus position to the default. 754 * If the camera does not support auto-focus, this is a no-op. 755 * 756 * @see #autoFocus(Camera.AutoFocusCallback) 757 */ 758 public final void cancelAutoFocus() 759 { 760 mAutoFocusCallback = null; 761 native_cancelAutoFocus(); 762 } 763 private native final void native_cancelAutoFocus(); 764 765 /** 766 * Callback interface used to signal the moment of actual image capture. 767 * 768 * @see #takePicture(ShutterCallback, PictureCallback, PictureCallback, PictureCallback) 769 */ 770 public interface ShutterCallback 771 { 772 /** 773 * Called as near as possible to the moment when a photo is captured 774 * from the sensor. This is a good opportunity to play a shutter sound 775 * or give other feedback of camera operation. This may be some time 776 * after the photo was triggered, but some time before the actual data 777 * is available. 778 */ 779 void onShutter(); 780 } 781 782 /** 783 * Callback interface used to supply image data from a photo capture. 784 * 785 * @see #takePicture(ShutterCallback, PictureCallback, PictureCallback, PictureCallback) 786 */ 787 public interface PictureCallback { 788 /** 789 * Called when image data is available after a picture is taken. 790 * The format of the data depends on the context of the callback 791 * and {@link Camera.Parameters} settings. 792 * 793 * @param data a byte array of the picture data 794 * @param camera the Camera service object 795 */ 796 void onPictureTaken(byte[] data, Camera camera); 797 }; 798 799 /** 800 * Equivalent to takePicture(shutter, raw, null, jpeg). 801 * 802 * @see #takePicture(ShutterCallback, PictureCallback, PictureCallback, PictureCallback) 803 */ 804 public final void takePicture(ShutterCallback shutter, PictureCallback raw, 805 PictureCallback jpeg) { 806 takePicture(shutter, raw, null, jpeg); 807 } 808 private native final void native_takePicture(int msgType); 809 810 /** 811 * Triggers an asynchronous image capture. The camera service will initiate 812 * a series of callbacks to the application as the image capture progresses. 813 * The shutter callback occurs after the image is captured. This can be used 814 * to trigger a sound to let the user know that image has been captured. The 815 * raw callback occurs when the raw image data is available (NOTE: the data 816 * will be null if there is no raw image callback buffer available or the 817 * raw image callback buffer is not large enough to hold the raw image). 818 * The postview callback occurs when a scaled, fully processed postview 819 * image is available (NOTE: not all hardware supports this). The jpeg 820 * callback occurs when the compressed image is available. If the 821 * application does not need a particular callback, a null can be passed 822 * instead of a callback method. 823 * 824 * <p>This method is only valid when preview is active (after 825 * {@link #startPreview()}). Preview will be stopped after the image is 826 * taken; callers must call {@link #startPreview()} again if they want to 827 * re-start preview or take more pictures. 828 * 829 * <p>After calling this method, you must not call {@link #startPreview()} 830 * or take another picture until the JPEG callback has returned. 831 * 832 * @param shutter the callback for image capture moment, or null 833 * @param raw the callback for raw (uncompressed) image data, or null 834 * @param postview callback with postview image data, may be null 835 * @param jpeg the callback for JPEG image data, or null 836 * 837 * @see #addRawImageCallbackBuffer(byte[]) 838 */ 839 public final void takePicture(ShutterCallback shutter, PictureCallback raw, 840 PictureCallback postview, PictureCallback jpeg) { 841 mShutterCallback = shutter; 842 mRawImageCallback = raw; 843 mPostviewCallback = postview; 844 mJpegCallback = jpeg; 845 846 // If callback is not set, do not send me callbacks. 847 int msgType = 0; 848 if (mShutterCallback != null) { 849 msgType |= CAMERA_MSG_SHUTTER; 850 } 851 if (mRawImageCallback != null) { 852 msgType |= CAMERA_MSG_RAW_IMAGE; 853 } 854 if (mPostviewCallback != null) { 855 msgType |= CAMERA_MSG_POSTVIEW_FRAME; 856 } 857 if (mJpegCallback != null) { 858 msgType |= CAMERA_MSG_COMPRESSED_IMAGE; 859 } 860 861 native_takePicture(msgType); 862 } 863 864 /** 865 * Zooms to the requested value smoothly. The driver will notify {@link 866 * OnZoomChangeListener} of the zoom value and whether zoom is stopped at 867 * the time. For example, suppose the current zoom is 0 and startSmoothZoom 868 * is called with value 3. The 869 * {@link Camera.OnZoomChangeListener#onZoomChange(int, boolean, Camera)} 870 * method will be called three times with zoom values 1, 2, and 3. 871 * Applications can call {@link #stopSmoothZoom} to stop the zoom earlier. 872 * Applications should not call startSmoothZoom again or change the zoom 873 * value before zoom stops. If the supplied zoom value equals to the current 874 * zoom value, no zoom callback will be generated. This method is supported 875 * if {@link android.hardware.Camera.Parameters#isSmoothZoomSupported} 876 * returns true. 877 * 878 * @param value zoom value. The valid range is 0 to {@link 879 * android.hardware.Camera.Parameters#getMaxZoom}. 880 * @throws IllegalArgumentException if the zoom value is invalid. 881 * @throws RuntimeException if the method fails. 882 * @see #setZoomChangeListener(OnZoomChangeListener) 883 */ 884 public native final void startSmoothZoom(int value); 885 886 /** 887 * Stops the smooth zoom. Applications should wait for the {@link 888 * OnZoomChangeListener} to know when the zoom is actually stopped. This 889 * method is supported if {@link 890 * android.hardware.Camera.Parameters#isSmoothZoomSupported} is true. 891 * 892 * @throws RuntimeException if the method fails. 893 */ 894 public native final void stopSmoothZoom(); 895 896 /** 897 * Set the clockwise rotation of preview display in degrees. This affects 898 * the preview frames and the picture displayed after snapshot. This method 899 * is useful for portrait mode applications. Note that preview display of 900 * front-facing cameras is flipped horizontally before the rotation, that 901 * is, the image is reflected along the central vertical axis of the camera 902 * sensor. So the users can see themselves as looking into a mirror. 903 * 904 * <p>This does not affect the order of byte array passed in {@link 905 * PreviewCallback#onPreviewFrame}, JPEG pictures, or recorded videos. This 906 * method is not allowed to be called during preview. 907 * 908 * <p>If you want to make the camera image show in the same orientation as 909 * the display, you can use the following code. 910 * <pre> 911 * public static void setCameraDisplayOrientation(Activity activity, 912 * int cameraId, android.hardware.Camera camera) { 913 * android.hardware.Camera.CameraInfo info = 914 * new android.hardware.Camera.CameraInfo(); 915 * android.hardware.Camera.getCameraInfo(cameraId, info); 916 * int rotation = activity.getWindowManager().getDefaultDisplay() 917 * .getRotation(); 918 * int degrees = 0; 919 * switch (rotation) { 920 * case Surface.ROTATION_0: degrees = 0; break; 921 * case Surface.ROTATION_90: degrees = 90; break; 922 * case Surface.ROTATION_180: degrees = 180; break; 923 * case Surface.ROTATION_270: degrees = 270; break; 924 * } 925 * 926 * int result; 927 * if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { 928 * result = (info.orientation + degrees) % 360; 929 * result = (360 - result) % 360; // compensate the mirror 930 * } else { // back-facing 931 * result = (info.orientation - degrees + 360) % 360; 932 * } 933 * camera.setDisplayOrientation(result); 934 * } 935 * </pre> 936 * @param degrees the angle that the picture will be rotated clockwise. 937 * Valid values are 0, 90, 180, and 270. The starting 938 * position is 0 (landscape). 939 * @see #setPreviewDisplay(SurfaceHolder) 940 */ 941 public native final void setDisplayOrientation(int degrees); 942 943 /** 944 * Callback interface for zoom changes during a smooth zoom operation. 945 * 946 * @see #setZoomChangeListener(OnZoomChangeListener) 947 * @see #startSmoothZoom(int) 948 */ 949 public interface OnZoomChangeListener 950 { 951 /** 952 * Called when the zoom value has changed during a smooth zoom. 953 * 954 * @param zoomValue the current zoom value. In smooth zoom mode, camera 955 * calls this for every new zoom value. 956 * @param stopped whether smooth zoom is stopped. If the value is true, 957 * this is the last zoom update for the application. 958 * @param camera the Camera service object 959 */ 960 void onZoomChange(int zoomValue, boolean stopped, Camera camera); 961 }; 962 963 /** 964 * Registers a listener to be notified when the zoom value is updated by the 965 * camera driver during smooth zoom. 966 * 967 * @param listener the listener to notify 968 * @see #startSmoothZoom(int) 969 */ 970 public final void setZoomChangeListener(OnZoomChangeListener listener) 971 { 972 mZoomListener = listener; 973 } 974 975 // Error codes match the enum in include/ui/Camera.h 976 977 /** 978 * Unspecified camera error. 979 * @see Camera.ErrorCallback 980 */ 981 public static final int CAMERA_ERROR_UNKNOWN = 1; 982 983 /** 984 * Media server died. In this case, the application must release the 985 * Camera object and instantiate a new one. 986 * @see Camera.ErrorCallback 987 */ 988 public static final int CAMERA_ERROR_SERVER_DIED = 100; 989 990 /** 991 * Callback interface for camera error notification. 992 * 993 * @see #setErrorCallback(ErrorCallback) 994 */ 995 public interface ErrorCallback 996 { 997 /** 998 * Callback for camera errors. 999 * @param error error code: 1000 * <ul> 1001 * <li>{@link #CAMERA_ERROR_UNKNOWN} 1002 * <li>{@link #CAMERA_ERROR_SERVER_DIED} 1003 * </ul> 1004 * @param camera the Camera service object 1005 */ 1006 void onError(int error, Camera camera); 1007 }; 1008 1009 /** 1010 * Registers a callback to be invoked when an error occurs. 1011 * @param cb The callback to run 1012 */ 1013 public final void setErrorCallback(ErrorCallback cb) 1014 { 1015 mErrorCallback = cb; 1016 } 1017 1018 private native final void native_setParameters(String params); 1019 private native final String native_getParameters(); 1020 1021 /** 1022 * Changes the settings for this Camera service. 1023 * 1024 * @param params the Parameters to use for this Camera service 1025 * @throws RuntimeException if any parameter is invalid or not supported. 1026 * @see #getParameters() 1027 */ 1028 public void setParameters(Parameters params) { 1029 native_setParameters(params.flatten()); 1030 } 1031 1032 /** 1033 * Returns the current settings for this Camera service. 1034 * If modifications are made to the returned Parameters, they must be passed 1035 * to {@link #setParameters(Camera.Parameters)} to take effect. 1036 * 1037 * @see #setParameters(Camera.Parameters) 1038 */ 1039 public Parameters getParameters() { 1040 Parameters p = new Parameters(); 1041 String s = native_getParameters(); 1042 p.unflatten(s); 1043 return p; 1044 } 1045 1046 /** 1047 * Image size (width and height dimensions). 1048 */ 1049 public class Size { 1050 /** 1051 * Sets the dimensions for pictures. 1052 * 1053 * @param w the photo width (pixels) 1054 * @param h the photo height (pixels) 1055 */ 1056 public Size(int w, int h) { 1057 width = w; 1058 height = h; 1059 } 1060 /** 1061 * Compares {@code obj} to this size. 1062 * 1063 * @param obj the object to compare this size with. 1064 * @return {@code true} if the width and height of {@code obj} is the 1065 * same as those of this size. {@code false} otherwise. 1066 */ 1067 @Override 1068 public boolean equals(Object obj) { 1069 if (!(obj instanceof Size)) { 1070 return false; 1071 } 1072 Size s = (Size) obj; 1073 return width == s.width && height == s.height; 1074 } 1075 @Override 1076 public int hashCode() { 1077 return width * 32713 + height; 1078 } 1079 /** width of the picture */ 1080 public int width; 1081 /** height of the picture */ 1082 public int height; 1083 }; 1084 1085 /** 1086 * Camera service settings. 1087 * 1088 * <p>To make camera parameters take effect, applications have to call 1089 * {@link Camera#setParameters(Camera.Parameters)}. For example, after 1090 * {@link Camera.Parameters#setWhiteBalance} is called, white balance is not 1091 * actually changed until {@link Camera#setParameters(Camera.Parameters)} 1092 * is called with the changed parameters object. 1093 * 1094 * <p>Different devices may have different camera capabilities, such as 1095 * picture size or flash modes. The application should query the camera 1096 * capabilities before setting parameters. For example, the application 1097 * should call {@link Camera.Parameters#getSupportedColorEffects()} before 1098 * calling {@link Camera.Parameters#setColorEffect(String)}. If the 1099 * camera does not support color effects, 1100 * {@link Camera.Parameters#getSupportedColorEffects()} will return null. 1101 */ 1102 public class Parameters { 1103 // Parameter keys to communicate with the camera driver. 1104 private static final String KEY_PREVIEW_SIZE = "preview-size"; 1105 private static final String KEY_PREVIEW_FORMAT = "preview-format"; 1106 private static final String KEY_PREVIEW_FRAME_RATE = "preview-frame-rate"; 1107 private static final String KEY_PREVIEW_FPS_RANGE = "preview-fps-range"; 1108 private static final String KEY_PICTURE_SIZE = "picture-size"; 1109 private static final String KEY_PICTURE_FORMAT = "picture-format"; 1110 private static final String KEY_JPEG_THUMBNAIL_SIZE = "jpeg-thumbnail-size"; 1111 private static final String KEY_JPEG_THUMBNAIL_WIDTH = "jpeg-thumbnail-width"; 1112 private static final String KEY_JPEG_THUMBNAIL_HEIGHT = "jpeg-thumbnail-height"; 1113 private static final String KEY_JPEG_THUMBNAIL_QUALITY = "jpeg-thumbnail-quality"; 1114 private static final String KEY_JPEG_QUALITY = "jpeg-quality"; 1115 private static final String KEY_ROTATION = "rotation"; 1116 private static final String KEY_GPS_LATITUDE = "gps-latitude"; 1117 private static final String KEY_GPS_LONGITUDE = "gps-longitude"; 1118 private static final String KEY_GPS_ALTITUDE = "gps-altitude"; 1119 private static final String KEY_GPS_TIMESTAMP = "gps-timestamp"; 1120 private static final String KEY_GPS_PROCESSING_METHOD = "gps-processing-method"; 1121 private static final String KEY_WHITE_BALANCE = "whitebalance"; 1122 private static final String KEY_EFFECT = "effect"; 1123 private static final String KEY_ANTIBANDING = "antibanding"; 1124 private static final String KEY_SCENE_MODE = "scene-mode"; 1125 private static final String KEY_FLASH_MODE = "flash-mode"; 1126 private static final String KEY_FOCUS_MODE = "focus-mode"; 1127 private static final String KEY_FOCAL_LENGTH = "focal-length"; 1128 private static final String KEY_HORIZONTAL_VIEW_ANGLE = "horizontal-view-angle"; 1129 private static final String KEY_VERTICAL_VIEW_ANGLE = "vertical-view-angle"; 1130 private static final String KEY_EXPOSURE_COMPENSATION = "exposure-compensation"; 1131 private static final String KEY_MAX_EXPOSURE_COMPENSATION = "max-exposure-compensation"; 1132 private static final String KEY_MIN_EXPOSURE_COMPENSATION = "min-exposure-compensation"; 1133 private static final String KEY_EXPOSURE_COMPENSATION_STEP = "exposure-compensation-step"; 1134 private static final String KEY_ZOOM = "zoom"; 1135 private static final String KEY_MAX_ZOOM = "max-zoom"; 1136 private static final String KEY_ZOOM_RATIOS = "zoom-ratios"; 1137 private static final String KEY_ZOOM_SUPPORTED = "zoom-supported"; 1138 private static final String KEY_SMOOTH_ZOOM_SUPPORTED = "smooth-zoom-supported"; 1139 private static final String KEY_FOCUS_DISTANCES = "focus-distances"; 1140 private static final String KEY_VIDEO_SIZE = "video-size"; 1141 private static final String KEY_PREFERRED_PREVIEW_SIZE_FOR_VIDEO = 1142 "preferred-preview-size-for-video"; 1143 1144 // Parameter key suffix for supported values. 1145 private static final String SUPPORTED_VALUES_SUFFIX = "-values"; 1146 1147 private static final String TRUE = "true"; 1148 1149 // Values for white balance settings. 1150 public static final String WHITE_BALANCE_AUTO = "auto"; 1151 public static final String WHITE_BALANCE_INCANDESCENT = "incandescent"; 1152 public static final String WHITE_BALANCE_FLUORESCENT = "fluorescent"; 1153 public static final String WHITE_BALANCE_WARM_FLUORESCENT = "warm-fluorescent"; 1154 public static final String WHITE_BALANCE_DAYLIGHT = "daylight"; 1155 public static final String WHITE_BALANCE_CLOUDY_DAYLIGHT = "cloudy-daylight"; 1156 public static final String WHITE_BALANCE_TWILIGHT = "twilight"; 1157 public static final String WHITE_BALANCE_SHADE = "shade"; 1158 1159 // Values for color effect settings. 1160 public static final String EFFECT_NONE = "none"; 1161 public static final String EFFECT_MONO = "mono"; 1162 public static final String EFFECT_NEGATIVE = "negative"; 1163 public static final String EFFECT_SOLARIZE = "solarize"; 1164 public static final String EFFECT_SEPIA = "sepia"; 1165 public static final String EFFECT_POSTERIZE = "posterize"; 1166 public static final String EFFECT_WHITEBOARD = "whiteboard"; 1167 public static final String EFFECT_BLACKBOARD = "blackboard"; 1168 public static final String EFFECT_AQUA = "aqua"; 1169 1170 // Values for antibanding settings. 1171 public static final String ANTIBANDING_AUTO = "auto"; 1172 public static final String ANTIBANDING_50HZ = "50hz"; 1173 public static final String ANTIBANDING_60HZ = "60hz"; 1174 public static final String ANTIBANDING_OFF = "off"; 1175 1176 // Values for flash mode settings. 1177 /** 1178 * Flash will not be fired. 1179 */ 1180 public static final String FLASH_MODE_OFF = "off"; 1181 1182 /** 1183 * Flash will be fired automatically when required. The flash may be fired 1184 * during preview, auto-focus, or snapshot depending on the driver. 1185 */ 1186 public static final String FLASH_MODE_AUTO = "auto"; 1187 1188 /** 1189 * Flash will always be fired during snapshot. The flash may also be 1190 * fired during preview or auto-focus depending on the driver. 1191 */ 1192 public static final String FLASH_MODE_ON = "on"; 1193 1194 /** 1195 * Flash will be fired in red-eye reduction mode. 1196 */ 1197 public static final String FLASH_MODE_RED_EYE = "red-eye"; 1198 1199 /** 1200 * Constant emission of light during preview, auto-focus and snapshot. 1201 * This can also be used for video recording. 1202 */ 1203 public static final String FLASH_MODE_TORCH = "torch"; 1204 1205 /** 1206 * Scene mode is off. 1207 */ 1208 public static final String SCENE_MODE_AUTO = "auto"; 1209 1210 /** 1211 * Take photos of fast moving objects. Same as {@link 1212 * #SCENE_MODE_SPORTS}. 1213 */ 1214 public static final String SCENE_MODE_ACTION = "action"; 1215 1216 /** 1217 * Take people pictures. 1218 */ 1219 public static final String SCENE_MODE_PORTRAIT = "portrait"; 1220 1221 /** 1222 * Take pictures on distant objects. 1223 */ 1224 public static final String SCENE_MODE_LANDSCAPE = "landscape"; 1225 1226 /** 1227 * Take photos at night. 1228 */ 1229 public static final String SCENE_MODE_NIGHT = "night"; 1230 1231 /** 1232 * Take people pictures at night. 1233 */ 1234 public static final String SCENE_MODE_NIGHT_PORTRAIT = "night-portrait"; 1235 1236 /** 1237 * Take photos in a theater. Flash light is off. 1238 */ 1239 public static final String SCENE_MODE_THEATRE = "theatre"; 1240 1241 /** 1242 * Take pictures on the beach. 1243 */ 1244 public static final String SCENE_MODE_BEACH = "beach"; 1245 1246 /** 1247 * Take pictures on the snow. 1248 */ 1249 public static final String SCENE_MODE_SNOW = "snow"; 1250 1251 /** 1252 * Take sunset photos. 1253 */ 1254 public static final String SCENE_MODE_SUNSET = "sunset"; 1255 1256 /** 1257 * Avoid blurry pictures (for example, due to hand shake). 1258 */ 1259 public static final String SCENE_MODE_STEADYPHOTO = "steadyphoto"; 1260 1261 /** 1262 * For shooting firework displays. 1263 */ 1264 public static final String SCENE_MODE_FIREWORKS = "fireworks"; 1265 1266 /** 1267 * Take photos of fast moving objects. Same as {@link 1268 * #SCENE_MODE_ACTION}. 1269 */ 1270 public static final String SCENE_MODE_SPORTS = "sports"; 1271 1272 /** 1273 * Take indoor low-light shot. 1274 */ 1275 public static final String SCENE_MODE_PARTY = "party"; 1276 1277 /** 1278 * Capture the naturally warm color of scenes lit by candles. 1279 */ 1280 public static final String SCENE_MODE_CANDLELIGHT = "candlelight"; 1281 1282 /** 1283 * Applications are looking for a barcode. Camera driver will be 1284 * optimized for barcode reading. 1285 */ 1286 public static final String SCENE_MODE_BARCODE = "barcode"; 1287 1288 /** 1289 * Auto-focus mode. Applications should call {@link 1290 * #autoFocus(AutoFocusCallback)} to start the focus in this mode. 1291 */ 1292 public static final String FOCUS_MODE_AUTO = "auto"; 1293 1294 /** 1295 * Focus is set at infinity. Applications should not call 1296 * {@link #autoFocus(AutoFocusCallback)} in this mode. 1297 */ 1298 public static final String FOCUS_MODE_INFINITY = "infinity"; 1299 1300 /** 1301 * Macro (close-up) focus mode. Applications should call 1302 * {@link #autoFocus(AutoFocusCallback)} to start the focus in this 1303 * mode. 1304 */ 1305 public static final String FOCUS_MODE_MACRO = "macro"; 1306 1307 /** 1308 * Focus is fixed. The camera is always in this mode if the focus is not 1309 * adjustable. If the camera has auto-focus, this mode can fix the 1310 * focus, which is usually at hyperfocal distance. Applications should 1311 * not call {@link #autoFocus(AutoFocusCallback)} in this mode. 1312 */ 1313 public static final String FOCUS_MODE_FIXED = "fixed"; 1314 1315 /** 1316 * Extended depth of field (EDOF). Focusing is done digitally and 1317 * continuously. Applications should not call {@link 1318 * #autoFocus(AutoFocusCallback)} in this mode. 1319 */ 1320 public static final String FOCUS_MODE_EDOF = "edof"; 1321 1322 /** 1323 * Continuous auto focus mode intended for video recording. The camera 1324 * continuously tries to focus. This is ideal for shooting video. 1325 * Applications still can call {@link 1326 * #takePicture(Camera.ShutterCallback, Camera.PictureCallback, 1327 * Camera.PictureCallback)} in this mode but the subject may not be in 1328 * focus. Auto focus starts when the parameter is set. Applications 1329 * should not call {@link #autoFocus(AutoFocusCallback)} in this mode. 1330 * To stop continuous focus, applications should change the focus mode 1331 * to other modes. 1332 */ 1333 public static final String FOCUS_MODE_CONTINUOUS_VIDEO = "continuous-video"; 1334 1335 // Indices for focus distance array. 1336 /** 1337 * The array index of near focus distance for use with 1338 * {@link #getFocusDistances(float[])}. 1339 */ 1340 public static final int FOCUS_DISTANCE_NEAR_INDEX = 0; 1341 1342 /** 1343 * The array index of optimal focus distance for use with 1344 * {@link #getFocusDistances(float[])}. 1345 */ 1346 public static final int FOCUS_DISTANCE_OPTIMAL_INDEX = 1; 1347 1348 /** 1349 * The array index of far focus distance for use with 1350 * {@link #getFocusDistances(float[])}. 1351 */ 1352 public static final int FOCUS_DISTANCE_FAR_INDEX = 2; 1353 1354 /** 1355 * The array index of minimum preview fps for use with {@link 1356 * #getPreviewFpsRange(int[])} or {@link 1357 * #getSupportedPreviewFpsRange()}. 1358 */ 1359 public static final int PREVIEW_FPS_MIN_INDEX = 0; 1360 1361 /** 1362 * The array index of maximum preview fps for use with {@link 1363 * #getPreviewFpsRange(int[])} or {@link 1364 * #getSupportedPreviewFpsRange()}. 1365 */ 1366 public static final int PREVIEW_FPS_MAX_INDEX = 1; 1367 1368 // Formats for setPreviewFormat and setPictureFormat. 1369 private static final String PIXEL_FORMAT_YUV422SP = "yuv422sp"; 1370 private static final String PIXEL_FORMAT_YUV420SP = "yuv420sp"; 1371 private static final String PIXEL_FORMAT_YUV422I = "yuv422i-yuyv"; 1372 private static final String PIXEL_FORMAT_YUV420P = "yuv420p"; 1373 private static final String PIXEL_FORMAT_RGB565 = "rgb565"; 1374 private static final String PIXEL_FORMAT_JPEG = "jpeg"; 1375 1376 private HashMap<String, String> mMap; 1377 1378 private Parameters() { 1379 mMap = new HashMap<String, String>(); 1380 } 1381 1382 /** 1383 * Writes the current Parameters to the log. 1384 * @hide 1385 * @deprecated 1386 */ 1387 public void dump() { 1388 Log.e(TAG, "dump: size=" + mMap.size()); 1389 for (String k : mMap.keySet()) { 1390 Log.e(TAG, "dump: " + k + "=" + mMap.get(k)); 1391 } 1392 } 1393 1394 /** 1395 * Creates a single string with all the parameters set in 1396 * this Parameters object. 1397 * <p>The {@link #unflatten(String)} method does the reverse.</p> 1398 * 1399 * @return a String with all values from this Parameters object, in 1400 * semi-colon delimited key-value pairs 1401 */ 1402 public String flatten() { 1403 StringBuilder flattened = new StringBuilder(); 1404 for (String k : mMap.keySet()) { 1405 flattened.append(k); 1406 flattened.append("="); 1407 flattened.append(mMap.get(k)); 1408 flattened.append(";"); 1409 } 1410 // chop off the extra semicolon at the end 1411 flattened.deleteCharAt(flattened.length()-1); 1412 return flattened.toString(); 1413 } 1414 1415 /** 1416 * Takes a flattened string of parameters and adds each one to 1417 * this Parameters object. 1418 * <p>The {@link #flatten()} method does the reverse.</p> 1419 * 1420 * @param flattened a String of parameters (key-value paired) that 1421 * are semi-colon delimited 1422 */ 1423 public void unflatten(String flattened) { 1424 mMap.clear(); 1425 1426 StringTokenizer tokenizer = new StringTokenizer(flattened, ";"); 1427 while (tokenizer.hasMoreElements()) { 1428 String kv = tokenizer.nextToken(); 1429 int pos = kv.indexOf('='); 1430 if (pos == -1) { 1431 continue; 1432 } 1433 String k = kv.substring(0, pos); 1434 String v = kv.substring(pos + 1); 1435 mMap.put(k, v); 1436 } 1437 } 1438 1439 public void remove(String key) { 1440 mMap.remove(key); 1441 } 1442 1443 /** 1444 * Sets a String parameter. 1445 * 1446 * @param key the key name for the parameter 1447 * @param value the String value of the parameter 1448 */ 1449 public void set(String key, String value) { 1450 if (key.indexOf('=') != -1 || key.indexOf(';') != -1) { 1451 Log.e(TAG, "Key \"" + key + "\" contains invalid character (= or ;)"); 1452 return; 1453 } 1454 if (value.indexOf('=') != -1 || value.indexOf(';') != -1) { 1455 Log.e(TAG, "Value \"" + value + "\" contains invalid character (= or ;)"); 1456 return; 1457 } 1458 1459 mMap.put(key, value); 1460 } 1461 1462 /** 1463 * Sets an integer parameter. 1464 * 1465 * @param key the key name for the parameter 1466 * @param value the int value of the parameter 1467 */ 1468 public void set(String key, int value) { 1469 mMap.put(key, Integer.toString(value)); 1470 } 1471 1472 /** 1473 * Returns the value of a String parameter. 1474 * 1475 * @param key the key name for the parameter 1476 * @return the String value of the parameter 1477 */ 1478 public String get(String key) { 1479 return mMap.get(key); 1480 } 1481 1482 /** 1483 * Returns the value of an integer parameter. 1484 * 1485 * @param key the key name for the parameter 1486 * @return the int value of the parameter 1487 */ 1488 public int getInt(String key) { 1489 return Integer.parseInt(mMap.get(key)); 1490 } 1491 1492 /** 1493 * Sets the dimensions for preview pictures. 1494 * 1495 * The sides of width and height are based on camera orientation. That 1496 * is, the preview size is the size before it is rotated by display 1497 * orientation. So applications need to consider the display orientation 1498 * while setting preview size. For example, suppose the camera supports 1499 * both 480x320 and 320x480 preview sizes. The application wants a 3:2 1500 * preview ratio. If the display orientation is set to 0 or 180, preview 1501 * size should be set to 480x320. If the display orientation is set to 1502 * 90 or 270, preview size should be set to 320x480. The display 1503 * orientation should also be considered while setting picture size and 1504 * thumbnail size. 1505 * 1506 * @param width the width of the pictures, in pixels 1507 * @param height the height of the pictures, in pixels 1508 * @see #setDisplayOrientation(int) 1509 * @see #getCameraInfo(int, CameraInfo) 1510 * @see #setPictureSize(int, int) 1511 * @see #setJpegThumbnailSize(int, int) 1512 */ 1513 public void setPreviewSize(int width, int height) { 1514 String v = Integer.toString(width) + "x" + Integer.toString(height); 1515 set(KEY_PREVIEW_SIZE, v); 1516 } 1517 1518 /** 1519 * Returns the dimensions setting for preview pictures. 1520 * 1521 * @return a Size object with the width and height setting 1522 * for the preview picture 1523 */ 1524 public Size getPreviewSize() { 1525 String pair = get(KEY_PREVIEW_SIZE); 1526 return strToSize(pair); 1527 } 1528 1529 /** 1530 * Gets the supported preview sizes. 1531 * 1532 * @return a list of Size object. This method will always return a list 1533 * with at least one element. 1534 */ 1535 public List<Size> getSupportedPreviewSizes() { 1536 String str = get(KEY_PREVIEW_SIZE + SUPPORTED_VALUES_SUFFIX); 1537 return splitSize(str); 1538 } 1539 1540 /** 1541 * Gets the supported video frame sizes that can be used by 1542 * MediaRecorder. 1543 * 1544 * If the returned list is not null, the returned list will contain at 1545 * least one Size and one of the sizes in the returned list must be 1546 * passed to MediaRecorder.setVideoSize() for camcorder application if 1547 * camera is used as the video source. In this case, the size of the 1548 * preview can be different from the resolution of the recorded video 1549 * during video recording. 1550 * 1551 * @return a list of Size object if camera has separate preview and 1552 * video output; otherwise, null is returned. 1553 * @see #getPreferredPreviewSizeForVideo() 1554 */ 1555 public List<Size> getSupportedVideoSizes() { 1556 String str = get(KEY_VIDEO_SIZE + SUPPORTED_VALUES_SUFFIX); 1557 return splitSize(str); 1558 } 1559 1560 /** 1561 * Returns the preferred or recommended preview size (width and height) 1562 * in pixels for video recording. Camcorder applications should 1563 * set the preview size to a value that is not larger than the 1564 * preferred preview size. In other words, the product of the width 1565 * and height of the preview size should not be larger than that of 1566 * the preferred preview size. In addition, we recommend to choose a 1567 * preview size that has the same aspect ratio as the resolution of 1568 * video to be recorded. 1569 * 1570 * @return the preferred preview size (width and height) in pixels for 1571 * video recording if getSupportedVideoSizes() does not return 1572 * null; otherwise, null is returned. 1573 * @see #getSupportedVideoSizes() 1574 */ 1575 public Size getPreferredPreviewSizeForVideo() { 1576 String pair = get(KEY_PREFERRED_PREVIEW_SIZE_FOR_VIDEO); 1577 return strToSize(pair); 1578 } 1579 1580 /** 1581 * Sets the dimensions for EXIF thumbnail in Jpeg picture. If 1582 * applications set both width and height to 0, EXIF will not contain 1583 * thumbnail. 1584 * 1585 * Applications need to consider the display orientation. See {@link 1586 * #setPreviewSize(int,int)} for reference. 1587 * 1588 * @param width the width of the thumbnail, in pixels 1589 * @param height the height of the thumbnail, in pixels 1590 * @see #setPreviewSize(int,int) 1591 */ 1592 public void setJpegThumbnailSize(int width, int height) { 1593 set(KEY_JPEG_THUMBNAIL_WIDTH, width); 1594 set(KEY_JPEG_THUMBNAIL_HEIGHT, height); 1595 } 1596 1597 /** 1598 * Returns the dimensions for EXIF thumbnail in Jpeg picture. 1599 * 1600 * @return a Size object with the height and width setting for the EXIF 1601 * thumbnails 1602 */ 1603 public Size getJpegThumbnailSize() { 1604 return new Size(getInt(KEY_JPEG_THUMBNAIL_WIDTH), 1605 getInt(KEY_JPEG_THUMBNAIL_HEIGHT)); 1606 } 1607 1608 /** 1609 * Gets the supported jpeg thumbnail sizes. 1610 * 1611 * @return a list of Size object. This method will always return a list 1612 * with at least two elements. Size 0,0 (no thumbnail) is always 1613 * supported. 1614 */ 1615 public List<Size> getSupportedJpegThumbnailSizes() { 1616 String str = get(KEY_JPEG_THUMBNAIL_SIZE + SUPPORTED_VALUES_SUFFIX); 1617 return splitSize(str); 1618 } 1619 1620 /** 1621 * Sets the quality of the EXIF thumbnail in Jpeg picture. 1622 * 1623 * @param quality the JPEG quality of the EXIF thumbnail. The range is 1 1624 * to 100, with 100 being the best. 1625 */ 1626 public void setJpegThumbnailQuality(int quality) { 1627 set(KEY_JPEG_THUMBNAIL_QUALITY, quality); 1628 } 1629 1630 /** 1631 * Returns the quality setting for the EXIF thumbnail in Jpeg picture. 1632 * 1633 * @return the JPEG quality setting of the EXIF thumbnail. 1634 */ 1635 public int getJpegThumbnailQuality() { 1636 return getInt(KEY_JPEG_THUMBNAIL_QUALITY); 1637 } 1638 1639 /** 1640 * Sets Jpeg quality of captured picture. 1641 * 1642 * @param quality the JPEG quality of captured picture. The range is 1 1643 * to 100, with 100 being the best. 1644 */ 1645 public void setJpegQuality(int quality) { 1646 set(KEY_JPEG_QUALITY, quality); 1647 } 1648 1649 /** 1650 * Returns the quality setting for the JPEG picture. 1651 * 1652 * @return the JPEG picture quality setting. 1653 */ 1654 public int getJpegQuality() { 1655 return getInt(KEY_JPEG_QUALITY); 1656 } 1657 1658 /** 1659 * Sets the rate at which preview frames are received. This is the 1660 * target frame rate. The actual frame rate depends on the driver. 1661 * 1662 * @param fps the frame rate (frames per second) 1663 * @deprecated replaced by {@link #setPreviewFpsRange(int,int)} 1664 */ 1665 @Deprecated 1666 public void setPreviewFrameRate(int fps) { 1667 set(KEY_PREVIEW_FRAME_RATE, fps); 1668 } 1669 1670 /** 1671 * Returns the setting for the rate at which preview frames are 1672 * received. This is the target frame rate. The actual frame rate 1673 * depends on the driver. 1674 * 1675 * @return the frame rate setting (frames per second) 1676 * @deprecated replaced by {@link #getPreviewFpsRange(int[])} 1677 */ 1678 @Deprecated 1679 public int getPreviewFrameRate() { 1680 return getInt(KEY_PREVIEW_FRAME_RATE); 1681 } 1682 1683 /** 1684 * Gets the supported preview frame rates. 1685 * 1686 * @return a list of supported preview frame rates. null if preview 1687 * frame rate setting is not supported. 1688 * @deprecated replaced by {@link #getSupportedPreviewFpsRange()} 1689 */ 1690 @Deprecated 1691 public List<Integer> getSupportedPreviewFrameRates() { 1692 String str = get(KEY_PREVIEW_FRAME_RATE + SUPPORTED_VALUES_SUFFIX); 1693 return splitInt(str); 1694 } 1695 1696 /** 1697 * Sets the maximum and maximum preview fps. This controls the rate of 1698 * preview frames received in {@link PreviewCallback}. The minimum and 1699 * maximum preview fps must be one of the elements from {@link 1700 * #getSupportedPreviewFpsRange}. 1701 * 1702 * @param min the minimum preview fps (scaled by 1000). 1703 * @param max the maximum preview fps (scaled by 1000). 1704 * @throws RuntimeException if fps range is invalid. 1705 * @see #setPreviewCallbackWithBuffer(Camera.PreviewCallback) 1706 * @see #getSupportedPreviewFpsRange() 1707 */ 1708 public void setPreviewFpsRange(int min, int max) { 1709 set(KEY_PREVIEW_FPS_RANGE, "" + min + "," + max); 1710 } 1711 1712 /** 1713 * Returns the current minimum and maximum preview fps. The values are 1714 * one of the elements returned by {@link #getSupportedPreviewFpsRange}. 1715 * 1716 * @return range the minimum and maximum preview fps (scaled by 1000). 1717 * @see #PREVIEW_FPS_MIN_INDEX 1718 * @see #PREVIEW_FPS_MAX_INDEX 1719 * @see #getSupportedPreviewFpsRange() 1720 */ 1721 public void getPreviewFpsRange(int[] range) { 1722 if (range == null || range.length != 2) { 1723 throw new IllegalArgumentException( 1724 "range must be an array with two elements."); 1725 } 1726 splitInt(get(KEY_PREVIEW_FPS_RANGE), range); 1727 } 1728 1729 /** 1730 * Gets the supported preview fps (frame-per-second) ranges. Each range 1731 * contains a minimum fps and maximum fps. If minimum fps equals to 1732 * maximum fps, the camera outputs frames in fixed frame rate. If not, 1733 * the camera outputs frames in auto frame rate. The actual frame rate 1734 * fluctuates between the minimum and the maximum. The values are 1735 * multiplied by 1000 and represented in integers. For example, if frame 1736 * rate is 26.623 frames per second, the value is 26623. 1737 * 1738 * @return a list of supported preview fps ranges. This method returns a 1739 * list with at least one element. Every element is an int array 1740 * of two values - minimum fps and maximum fps. The list is 1741 * sorted from small to large (first by maximum fps and then 1742 * minimum fps). 1743 * @see #PREVIEW_FPS_MIN_INDEX 1744 * @see #PREVIEW_FPS_MAX_INDEX 1745 */ 1746 public List<int[]> getSupportedPreviewFpsRange() { 1747 String str = get(KEY_PREVIEW_FPS_RANGE + SUPPORTED_VALUES_SUFFIX); 1748 return splitRange(str); 1749 } 1750 1751 /** 1752 * Sets the image format for preview pictures. 1753 * <p>If this is never called, the default format will be 1754 * {@link android.graphics.ImageFormat#NV21}, which 1755 * uses the NV21 encoding format.</p> 1756 * 1757 * @param pixel_format the desired preview picture format, defined 1758 * by one of the {@link android.graphics.ImageFormat} constants. 1759 * (E.g., <var>ImageFormat.NV21</var> (default), 1760 * <var>ImageFormat.RGB_565</var>, or 1761 * <var>ImageFormat.JPEG</var>) 1762 * @see android.graphics.ImageFormat 1763 */ 1764 public void setPreviewFormat(int pixel_format) { 1765 String s = cameraFormatForPixelFormat(pixel_format); 1766 if (s == null) { 1767 throw new IllegalArgumentException( 1768 "Invalid pixel_format=" + pixel_format); 1769 } 1770 1771 set(KEY_PREVIEW_FORMAT, s); 1772 } 1773 1774 /** 1775 * Returns the image format for preview frames got from 1776 * {@link PreviewCallback}. 1777 * 1778 * @return the preview format. 1779 * @see android.graphics.ImageFormat 1780 */ 1781 public int getPreviewFormat() { 1782 return pixelFormatForCameraFormat(get(KEY_PREVIEW_FORMAT)); 1783 } 1784 1785 /** 1786 * Gets the supported preview formats. {@link android.graphics.ImageFormat#NV21} 1787 * is always supported. {@link android.graphics.ImageFormat#YV12} 1788 * is always supported since API level 12. 1789 * 1790 * @return a list of supported preview formats. This method will always 1791 * return a list with at least one element. 1792 * @see android.graphics.ImageFormat 1793 */ 1794 public List<Integer> getSupportedPreviewFormats() { 1795 String str = get(KEY_PREVIEW_FORMAT + SUPPORTED_VALUES_SUFFIX); 1796 ArrayList<Integer> formats = new ArrayList<Integer>(); 1797 for (String s : split(str)) { 1798 int f = pixelFormatForCameraFormat(s); 1799 if (f == ImageFormat.UNKNOWN) continue; 1800 formats.add(f); 1801 } 1802 return formats; 1803 } 1804 1805 /** 1806 * Sets the dimensions for pictures. 1807 * 1808 * Applications need to consider the display orientation. See {@link 1809 * #setPreviewSize(int,int)} for reference. 1810 * 1811 * @param width the width for pictures, in pixels 1812 * @param height the height for pictures, in pixels 1813 * @see #setPreviewSize(int,int) 1814 * 1815 */ 1816 public void setPictureSize(int width, int height) { 1817 String v = Integer.toString(width) + "x" + Integer.toString(height); 1818 set(KEY_PICTURE_SIZE, v); 1819 } 1820 1821 /** 1822 * Returns the dimension setting for pictures. 1823 * 1824 * @return a Size object with the height and width setting 1825 * for pictures 1826 */ 1827 public Size getPictureSize() { 1828 String pair = get(KEY_PICTURE_SIZE); 1829 return strToSize(pair); 1830 } 1831 1832 /** 1833 * Gets the supported picture sizes. 1834 * 1835 * @return a list of supported picture sizes. This method will always 1836 * return a list with at least one element. 1837 */ 1838 public List<Size> getSupportedPictureSizes() { 1839 String str = get(KEY_PICTURE_SIZE + SUPPORTED_VALUES_SUFFIX); 1840 return splitSize(str); 1841 } 1842 1843 /** 1844 * Sets the image format for pictures. 1845 * 1846 * @param pixel_format the desired picture format 1847 * (<var>ImageFormat.NV21</var>, 1848 * <var>ImageFormat.RGB_565</var>, or 1849 * <var>ImageFormat.JPEG</var>) 1850 * @see android.graphics.ImageFormat 1851 */ 1852 public void setPictureFormat(int pixel_format) { 1853 String s = cameraFormatForPixelFormat(pixel_format); 1854 if (s == null) { 1855 throw new IllegalArgumentException( 1856 "Invalid pixel_format=" + pixel_format); 1857 } 1858 1859 set(KEY_PICTURE_FORMAT, s); 1860 } 1861 1862 /** 1863 * Returns the image format for pictures. 1864 * 1865 * @return the picture format 1866 * @see android.graphics.ImageFormat 1867 */ 1868 public int getPictureFormat() { 1869 return pixelFormatForCameraFormat(get(KEY_PICTURE_FORMAT)); 1870 } 1871 1872 /** 1873 * Gets the supported picture formats. 1874 * 1875 * @return supported picture formats. This method will always return a 1876 * list with at least one element. 1877 * @see android.graphics.ImageFormat 1878 */ 1879 public List<Integer> getSupportedPictureFormats() { 1880 String str = get(KEY_PICTURE_FORMAT + SUPPORTED_VALUES_SUFFIX); 1881 ArrayList<Integer> formats = new ArrayList<Integer>(); 1882 for (String s : split(str)) { 1883 int f = pixelFormatForCameraFormat(s); 1884 if (f == ImageFormat.UNKNOWN) continue; 1885 formats.add(f); 1886 } 1887 return formats; 1888 } 1889 1890 private String cameraFormatForPixelFormat(int pixel_format) { 1891 switch(pixel_format) { 1892 case ImageFormat.NV16: return PIXEL_FORMAT_YUV422SP; 1893 case ImageFormat.NV21: return PIXEL_FORMAT_YUV420SP; 1894 case ImageFormat.YUY2: return PIXEL_FORMAT_YUV422I; 1895 case ImageFormat.YV12: return PIXEL_FORMAT_YUV420P; 1896 case ImageFormat.RGB_565: return PIXEL_FORMAT_RGB565; 1897 case ImageFormat.JPEG: return PIXEL_FORMAT_JPEG; 1898 default: return null; 1899 } 1900 } 1901 1902 private int pixelFormatForCameraFormat(String format) { 1903 if (format == null) 1904 return ImageFormat.UNKNOWN; 1905 1906 if (format.equals(PIXEL_FORMAT_YUV422SP)) 1907 return ImageFormat.NV16; 1908 1909 if (format.equals(PIXEL_FORMAT_YUV420SP)) 1910 return ImageFormat.NV21; 1911 1912 if (format.equals(PIXEL_FORMAT_YUV422I)) 1913 return ImageFormat.YUY2; 1914 1915 if (format.equals(PIXEL_FORMAT_YUV420P)) 1916 return ImageFormat.YV12; 1917 1918 if (format.equals(PIXEL_FORMAT_RGB565)) 1919 return ImageFormat.RGB_565; 1920 1921 if (format.equals(PIXEL_FORMAT_JPEG)) 1922 return ImageFormat.JPEG; 1923 1924 return ImageFormat.UNKNOWN; 1925 } 1926 1927 /** 1928 * Sets the rotation angle in degrees relative to the orientation of 1929 * the camera. This affects the pictures returned from JPEG {@link 1930 * PictureCallback}. The camera driver may set orientation in the 1931 * EXIF header without rotating the picture. Or the driver may rotate 1932 * the picture and the EXIF thumbnail. If the Jpeg picture is rotated, 1933 * the orientation in the EXIF header will be missing or 1 (row #0 is 1934 * top and column #0 is left side). 1935 * 1936 * <p>If applications want to rotate the picture to match the orientation 1937 * of what users see, apps should use {@link 1938 * android.view.OrientationEventListener} and {@link CameraInfo}. 1939 * The value from OrientationEventListener is relative to the natural 1940 * orientation of the device. CameraInfo.orientation is the angle 1941 * between camera orientation and natural device orientation. The sum 1942 * of the two is the rotation angle for back-facing camera. The 1943 * difference of the two is the rotation angle for front-facing camera. 1944 * Note that the JPEG pictures of front-facing cameras are not mirrored 1945 * as in preview display. 1946 * 1947 * <p>For example, suppose the natural orientation of the device is 1948 * portrait. The device is rotated 270 degrees clockwise, so the device 1949 * orientation is 270. Suppose a back-facing camera sensor is mounted in 1950 * landscape and the top side of the camera sensor is aligned with the 1951 * right edge of the display in natural orientation. So the camera 1952 * orientation is 90. The rotation should be set to 0 (270 + 90). 1953 * 1954 * <p>The reference code is as follows. 1955 * 1956 * <pre> 1957 * public void public void onOrientationChanged(int orientation) { 1958 * if (orientation == ORIENTATION_UNKNOWN) return; 1959 * android.hardware.Camera.CameraInfo info = 1960 * new android.hardware.Camera.CameraInfo(); 1961 * android.hardware.Camera.getCameraInfo(cameraId, info); 1962 * orientation = (orientation + 45) / 90 * 90; 1963 * int rotation = 0; 1964 * if (info.facing == CameraInfo.CAMERA_FACING_FRONT) { 1965 * rotation = (info.orientation - orientation + 360) % 360; 1966 * } else { // back-facing camera 1967 * rotation = (info.orientation + orientation) % 360; 1968 * } 1969 * mParameters.setRotation(rotation); 1970 * } 1971 * </pre> 1972 * 1973 * @param rotation The rotation angle in degrees relative to the 1974 * orientation of the camera. Rotation can only be 0, 1975 * 90, 180 or 270. 1976 * @throws IllegalArgumentException if rotation value is invalid. 1977 * @see android.view.OrientationEventListener 1978 * @see #getCameraInfo(int, CameraInfo) 1979 */ 1980 public void setRotation(int rotation) { 1981 if (rotation == 0 || rotation == 90 || rotation == 180 1982 || rotation == 270) { 1983 set(KEY_ROTATION, Integer.toString(rotation)); 1984 } else { 1985 throw new IllegalArgumentException( 1986 "Invalid rotation=" + rotation); 1987 } 1988 } 1989 1990 /** 1991 * Sets GPS latitude coordinate. This will be stored in JPEG EXIF 1992 * header. 1993 * 1994 * @param latitude GPS latitude coordinate. 1995 */ 1996 public void setGpsLatitude(double latitude) { 1997 set(KEY_GPS_LATITUDE, Double.toString(latitude)); 1998 } 1999 2000 /** 2001 * Sets GPS longitude coordinate. This will be stored in JPEG EXIF 2002 * header. 2003 * 2004 * @param longitude GPS longitude coordinate. 2005 */ 2006 public void setGpsLongitude(double longitude) { 2007 set(KEY_GPS_LONGITUDE, Double.toString(longitude)); 2008 } 2009 2010 /** 2011 * Sets GPS altitude. This will be stored in JPEG EXIF header. 2012 * 2013 * @param altitude GPS altitude in meters. 2014 */ 2015 public void setGpsAltitude(double altitude) { 2016 set(KEY_GPS_ALTITUDE, Double.toString(altitude)); 2017 } 2018 2019 /** 2020 * Sets GPS timestamp. This will be stored in JPEG EXIF header. 2021 * 2022 * @param timestamp GPS timestamp (UTC in seconds since January 1, 2023 * 1970). 2024 */ 2025 public void setGpsTimestamp(long timestamp) { 2026 set(KEY_GPS_TIMESTAMP, Long.toString(timestamp)); 2027 } 2028 2029 /** 2030 * Sets GPS processing method. It will store up to 32 characters 2031 * in JPEG EXIF header. 2032 * 2033 * @param processing_method The processing method to get this location. 2034 */ 2035 public void setGpsProcessingMethod(String processing_method) { 2036 set(KEY_GPS_PROCESSING_METHOD, processing_method); 2037 } 2038 2039 /** 2040 * Removes GPS latitude, longitude, altitude, and timestamp from the 2041 * parameters. 2042 */ 2043 public void removeGpsData() { 2044 remove(KEY_GPS_LATITUDE); 2045 remove(KEY_GPS_LONGITUDE); 2046 remove(KEY_GPS_ALTITUDE); 2047 remove(KEY_GPS_TIMESTAMP); 2048 remove(KEY_GPS_PROCESSING_METHOD); 2049 } 2050 2051 /** 2052 * Gets the current white balance setting. 2053 * 2054 * @return current white balance. null if white balance setting is not 2055 * supported. 2056 * @see #WHITE_BALANCE_AUTO 2057 * @see #WHITE_BALANCE_INCANDESCENT 2058 * @see #WHITE_BALANCE_FLUORESCENT 2059 * @see #WHITE_BALANCE_WARM_FLUORESCENT 2060 * @see #WHITE_BALANCE_DAYLIGHT 2061 * @see #WHITE_BALANCE_CLOUDY_DAYLIGHT 2062 * @see #WHITE_BALANCE_TWILIGHT 2063 * @see #WHITE_BALANCE_SHADE 2064 * 2065 */ 2066 public String getWhiteBalance() { 2067 return get(KEY_WHITE_BALANCE); 2068 } 2069 2070 /** 2071 * Sets the white balance. 2072 * 2073 * @param value new white balance. 2074 * @see #getWhiteBalance() 2075 */ 2076 public void setWhiteBalance(String value) { 2077 set(KEY_WHITE_BALANCE, value); 2078 } 2079 2080 /** 2081 * Gets the supported white balance. 2082 * 2083 * @return a list of supported white balance. null if white balance 2084 * setting is not supported. 2085 * @see #getWhiteBalance() 2086 */ 2087 public List<String> getSupportedWhiteBalance() { 2088 String str = get(KEY_WHITE_BALANCE + SUPPORTED_VALUES_SUFFIX); 2089 return split(str); 2090 } 2091 2092 /** 2093 * Gets the current color effect setting. 2094 * 2095 * @return current color effect. null if color effect 2096 * setting is not supported. 2097 * @see #EFFECT_NONE 2098 * @see #EFFECT_MONO 2099 * @see #EFFECT_NEGATIVE 2100 * @see #EFFECT_SOLARIZE 2101 * @see #EFFECT_SEPIA 2102 * @see #EFFECT_POSTERIZE 2103 * @see #EFFECT_WHITEBOARD 2104 * @see #EFFECT_BLACKBOARD 2105 * @see #EFFECT_AQUA 2106 */ 2107 public String getColorEffect() { 2108 return get(KEY_EFFECT); 2109 } 2110 2111 /** 2112 * Sets the current color effect setting. 2113 * 2114 * @param value new color effect. 2115 * @see #getColorEffect() 2116 */ 2117 public void setColorEffect(String value) { 2118 set(KEY_EFFECT, value); 2119 } 2120 2121 /** 2122 * Gets the supported color effects. 2123 * 2124 * @return a list of supported color effects. null if color effect 2125 * setting is not supported. 2126 * @see #getColorEffect() 2127 */ 2128 public List<String> getSupportedColorEffects() { 2129 String str = get(KEY_EFFECT + SUPPORTED_VALUES_SUFFIX); 2130 return split(str); 2131 } 2132 2133 2134 /** 2135 * Gets the current antibanding setting. 2136 * 2137 * @return current antibanding. null if antibanding setting is not 2138 * supported. 2139 * @see #ANTIBANDING_AUTO 2140 * @see #ANTIBANDING_50HZ 2141 * @see #ANTIBANDING_60HZ 2142 * @see #ANTIBANDING_OFF 2143 */ 2144 public String getAntibanding() { 2145 return get(KEY_ANTIBANDING); 2146 } 2147 2148 /** 2149 * Sets the antibanding. 2150 * 2151 * @param antibanding new antibanding value. 2152 * @see #getAntibanding() 2153 */ 2154 public void setAntibanding(String antibanding) { 2155 set(KEY_ANTIBANDING, antibanding); 2156 } 2157 2158 /** 2159 * Gets the supported antibanding values. 2160 * 2161 * @return a list of supported antibanding values. null if antibanding 2162 * setting is not supported. 2163 * @see #getAntibanding() 2164 */ 2165 public List<String> getSupportedAntibanding() { 2166 String str = get(KEY_ANTIBANDING + SUPPORTED_VALUES_SUFFIX); 2167 return split(str); 2168 } 2169 2170 /** 2171 * Gets the current scene mode setting. 2172 * 2173 * @return one of SCENE_MODE_XXX string constant. null if scene mode 2174 * setting is not supported. 2175 * @see #SCENE_MODE_AUTO 2176 * @see #SCENE_MODE_ACTION 2177 * @see #SCENE_MODE_PORTRAIT 2178 * @see #SCENE_MODE_LANDSCAPE 2179 * @see #SCENE_MODE_NIGHT 2180 * @see #SCENE_MODE_NIGHT_PORTRAIT 2181 * @see #SCENE_MODE_THEATRE 2182 * @see #SCENE_MODE_BEACH 2183 * @see #SCENE_MODE_SNOW 2184 * @see #SCENE_MODE_SUNSET 2185 * @see #SCENE_MODE_STEADYPHOTO 2186 * @see #SCENE_MODE_FIREWORKS 2187 * @see #SCENE_MODE_SPORTS 2188 * @see #SCENE_MODE_PARTY 2189 * @see #SCENE_MODE_CANDLELIGHT 2190 */ 2191 public String getSceneMode() { 2192 return get(KEY_SCENE_MODE); 2193 } 2194 2195 /** 2196 * Sets the scene mode. Changing scene mode may override other 2197 * parameters (such as flash mode, focus mode, white balance). For 2198 * example, suppose originally flash mode is on and supported flash 2199 * modes are on/off. In night scene mode, both flash mode and supported 2200 * flash mode may be changed to off. After setting scene mode, 2201 * applications should call getParameters to know if some parameters are 2202 * changed. 2203 * 2204 * @param value scene mode. 2205 * @see #getSceneMode() 2206 */ 2207 public void setSceneMode(String value) { 2208 set(KEY_SCENE_MODE, value); 2209 } 2210 2211 /** 2212 * Gets the supported scene modes. 2213 * 2214 * @return a list of supported scene modes. null if scene mode setting 2215 * is not supported. 2216 * @see #getSceneMode() 2217 */ 2218 public List<String> getSupportedSceneModes() { 2219 String str = get(KEY_SCENE_MODE + SUPPORTED_VALUES_SUFFIX); 2220 return split(str); 2221 } 2222 2223 /** 2224 * Gets the current flash mode setting. 2225 * 2226 * @return current flash mode. null if flash mode setting is not 2227 * supported. 2228 * @see #FLASH_MODE_OFF 2229 * @see #FLASH_MODE_AUTO 2230 * @see #FLASH_MODE_ON 2231 * @see #FLASH_MODE_RED_EYE 2232 * @see #FLASH_MODE_TORCH 2233 */ 2234 public String getFlashMode() { 2235 return get(KEY_FLASH_MODE); 2236 } 2237 2238 /** 2239 * Sets the flash mode. 2240 * 2241 * @param value flash mode. 2242 * @see #getFlashMode() 2243 */ 2244 public void setFlashMode(String value) { 2245 set(KEY_FLASH_MODE, value); 2246 } 2247 2248 /** 2249 * Gets the supported flash modes. 2250 * 2251 * @return a list of supported flash modes. null if flash mode setting 2252 * is not supported. 2253 * @see #getFlashMode() 2254 */ 2255 public List<String> getSupportedFlashModes() { 2256 String str = get(KEY_FLASH_MODE + SUPPORTED_VALUES_SUFFIX); 2257 return split(str); 2258 } 2259 2260 /** 2261 * Gets the current focus mode setting. 2262 * 2263 * @return current focus mode. This method will always return a non-null 2264 * value. Applications should call {@link 2265 * #autoFocus(AutoFocusCallback)} to start the focus if focus 2266 * mode is FOCUS_MODE_AUTO or FOCUS_MODE_MACRO. 2267 * @see #FOCUS_MODE_AUTO 2268 * @see #FOCUS_MODE_INFINITY 2269 * @see #FOCUS_MODE_MACRO 2270 * @see #FOCUS_MODE_FIXED 2271 * @see #FOCUS_MODE_EDOF 2272 * @see #FOCUS_MODE_CONTINUOUS_VIDEO 2273 */ 2274 public String getFocusMode() { 2275 return get(KEY_FOCUS_MODE); 2276 } 2277 2278 /** 2279 * Sets the focus mode. 2280 * 2281 * @param value focus mode. 2282 * @see #getFocusMode() 2283 */ 2284 public void setFocusMode(String value) { 2285 set(KEY_FOCUS_MODE, value); 2286 } 2287 2288 /** 2289 * Gets the supported focus modes. 2290 * 2291 * @return a list of supported focus modes. This method will always 2292 * return a list with at least one element. 2293 * @see #getFocusMode() 2294 */ 2295 public List<String> getSupportedFocusModes() { 2296 String str = get(KEY_FOCUS_MODE + SUPPORTED_VALUES_SUFFIX); 2297 return split(str); 2298 } 2299 2300 /** 2301 * Gets the focal length (in millimeter) of the camera. 2302 * 2303 * @return the focal length. This method will always return a valid 2304 * value. 2305 */ 2306 public float getFocalLength() { 2307 return Float.parseFloat(get(KEY_FOCAL_LENGTH)); 2308 } 2309 2310 /** 2311 * Gets the horizontal angle of view in degrees. 2312 * 2313 * @return horizontal angle of view. This method will always return a 2314 * valid value. 2315 */ 2316 public float getHorizontalViewAngle() { 2317 return Float.parseFloat(get(KEY_HORIZONTAL_VIEW_ANGLE)); 2318 } 2319 2320 /** 2321 * Gets the vertical angle of view in degrees. 2322 * 2323 * @return vertical angle of view. This method will always return a 2324 * valid value. 2325 */ 2326 public float getVerticalViewAngle() { 2327 return Float.parseFloat(get(KEY_VERTICAL_VIEW_ANGLE)); 2328 } 2329 2330 /** 2331 * Gets the current exposure compensation index. 2332 * 2333 * @return current exposure compensation index. The range is {@link 2334 * #getMinExposureCompensation} to {@link 2335 * #getMaxExposureCompensation}. 0 means exposure is not 2336 * adjusted. 2337 */ 2338 public int getExposureCompensation() { 2339 return getInt(KEY_EXPOSURE_COMPENSATION, 0); 2340 } 2341 2342 /** 2343 * Sets the exposure compensation index. 2344 * 2345 * @param value exposure compensation index. The valid value range is 2346 * from {@link #getMinExposureCompensation} (inclusive) to {@link 2347 * #getMaxExposureCompensation} (inclusive). 0 means exposure is 2348 * not adjusted. Application should call 2349 * getMinExposureCompensation and getMaxExposureCompensation to 2350 * know if exposure compensation is supported. 2351 */ 2352 public void setExposureCompensation(int value) { 2353 set(KEY_EXPOSURE_COMPENSATION, value); 2354 } 2355 2356 /** 2357 * Gets the maximum exposure compensation index. 2358 * 2359 * @return maximum exposure compensation index (>=0). If both this 2360 * method and {@link #getMinExposureCompensation} return 0, 2361 * exposure compensation is not supported. 2362 */ 2363 public int getMaxExposureCompensation() { 2364 return getInt(KEY_MAX_EXPOSURE_COMPENSATION, 0); 2365 } 2366 2367 /** 2368 * Gets the minimum exposure compensation index. 2369 * 2370 * @return minimum exposure compensation index (<=0). If both this 2371 * method and {@link #getMaxExposureCompensation} return 0, 2372 * exposure compensation is not supported. 2373 */ 2374 public int getMinExposureCompensation() { 2375 return getInt(KEY_MIN_EXPOSURE_COMPENSATION, 0); 2376 } 2377 2378 /** 2379 * Gets the exposure compensation step. 2380 * 2381 * @return exposure compensation step. Applications can get EV by 2382 * multiplying the exposure compensation index and step. Ex: if 2383 * exposure compensation index is -6 and step is 0.333333333, EV 2384 * is -2. 2385 */ 2386 public float getExposureCompensationStep() { 2387 return getFloat(KEY_EXPOSURE_COMPENSATION_STEP, 0); 2388 } 2389 2390 /** 2391 * Gets current zoom value. This also works when smooth zoom is in 2392 * progress. Applications should check {@link #isZoomSupported} before 2393 * using this method. 2394 * 2395 * @return the current zoom value. The range is 0 to {@link 2396 * #getMaxZoom}. 0 means the camera is not zoomed. 2397 */ 2398 public int getZoom() { 2399 return getInt(KEY_ZOOM, 0); 2400 } 2401 2402 /** 2403 * Sets current zoom value. If the camera is zoomed (value > 0), the 2404 * actual picture size may be smaller than picture size setting. 2405 * Applications can check the actual picture size after picture is 2406 * returned from {@link PictureCallback}. The preview size remains the 2407 * same in zoom. Applications should check {@link #isZoomSupported} 2408 * before using this method. 2409 * 2410 * @param value zoom value. The valid range is 0 to {@link #getMaxZoom}. 2411 */ 2412 public void setZoom(int value) { 2413 set(KEY_ZOOM, value); 2414 } 2415 2416 /** 2417 * Returns true if zoom is supported. Applications should call this 2418 * before using other zoom methods. 2419 * 2420 * @return true if zoom is supported. 2421 */ 2422 public boolean isZoomSupported() { 2423 String str = get(KEY_ZOOM_SUPPORTED); 2424 return TRUE.equals(str); 2425 } 2426 2427 /** 2428 * Gets the maximum zoom value allowed for snapshot. This is the maximum 2429 * value that applications can set to {@link #setZoom(int)}. 2430 * Applications should call {@link #isZoomSupported} before using this 2431 * method. This value may change in different preview size. Applications 2432 * should call this again after setting preview size. 2433 * 2434 * @return the maximum zoom value supported by the camera. 2435 */ 2436 public int getMaxZoom() { 2437 return getInt(KEY_MAX_ZOOM, 0); 2438 } 2439 2440 /** 2441 * Gets the zoom ratios of all zoom values. Applications should check 2442 * {@link #isZoomSupported} before using this method. 2443 * 2444 * @return the zoom ratios in 1/100 increments. Ex: a zoom of 3.2x is 2445 * returned as 320. The number of elements is {@link 2446 * #getMaxZoom} + 1. The list is sorted from small to large. The 2447 * first element is always 100. The last element is the zoom 2448 * ratio of the maximum zoom value. 2449 */ 2450 public List<Integer> getZoomRatios() { 2451 return splitInt(get(KEY_ZOOM_RATIOS)); 2452 } 2453 2454 /** 2455 * Returns true if smooth zoom is supported. Applications should call 2456 * this before using other smooth zoom methods. 2457 * 2458 * @return true if smooth zoom is supported. 2459 */ 2460 public boolean isSmoothZoomSupported() { 2461 String str = get(KEY_SMOOTH_ZOOM_SUPPORTED); 2462 return TRUE.equals(str); 2463 } 2464 2465 /** 2466 * Gets the distances from the camera to where an object appears to be 2467 * in focus. The object is sharpest at the optimal focus distance. The 2468 * depth of field is the far focus distance minus near focus distance. 2469 * 2470 * Focus distances may change after calling {@link 2471 * #autoFocus(AutoFocusCallback)}, {@link #cancelAutoFocus}, or {@link 2472 * #startPreview()}. Applications can call {@link #getParameters()} 2473 * and this method anytime to get the latest focus distances. If the 2474 * focus mode is FOCUS_MODE_CONTINUOUS_VIDEO, focus distances may change 2475 * from time to time. 2476 * 2477 * This method is intended to estimate the distance between the camera 2478 * and the subject. After autofocus, the subject distance may be within 2479 * near and far focus distance. However, the precision depends on the 2480 * camera hardware, autofocus algorithm, the focus area, and the scene. 2481 * The error can be large and it should be only used as a reference. 2482 * 2483 * Far focus distance >= optimal focus distance >= near focus distance. 2484 * If the focus distance is infinity, the value will be 2485 * Float.POSITIVE_INFINITY. 2486 * 2487 * @param output focus distances in meters. output must be a float 2488 * array with three elements. Near focus distance, optimal focus 2489 * distance, and far focus distance will be filled in the array. 2490 * @see #FOCUS_DISTANCE_NEAR_INDEX 2491 * @see #FOCUS_DISTANCE_OPTIMAL_INDEX 2492 * @see #FOCUS_DISTANCE_FAR_INDEX 2493 */ 2494 public void getFocusDistances(float[] output) { 2495 if (output == null || output.length != 3) { 2496 throw new IllegalArgumentException( 2497 "output must be an float array with three elements."); 2498 } 2499 splitFloat(get(KEY_FOCUS_DISTANCES), output); 2500 } 2501 2502 // Splits a comma delimited string to an ArrayList of String. 2503 // Return null if the passing string is null or the size is 0. 2504 private ArrayList<String> split(String str) { 2505 if (str == null) return null; 2506 2507 // Use StringTokenizer because it is faster than split. 2508 StringTokenizer tokenizer = new StringTokenizer(str, ","); 2509 ArrayList<String> substrings = new ArrayList<String>(); 2510 while (tokenizer.hasMoreElements()) { 2511 substrings.add(tokenizer.nextToken()); 2512 } 2513 return substrings; 2514 } 2515 2516 // Splits a comma delimited string to an ArrayList of Integer. 2517 // Return null if the passing string is null or the size is 0. 2518 private ArrayList<Integer> splitInt(String str) { 2519 if (str == null) return null; 2520 2521 StringTokenizer tokenizer = new StringTokenizer(str, ","); 2522 ArrayList<Integer> substrings = new ArrayList<Integer>(); 2523 while (tokenizer.hasMoreElements()) { 2524 String token = tokenizer.nextToken(); 2525 substrings.add(Integer.parseInt(token)); 2526 } 2527 if (substrings.size() == 0) return null; 2528 return substrings; 2529 } 2530 2531 private void splitInt(String str, int[] output) { 2532 if (str == null) return; 2533 2534 StringTokenizer tokenizer = new StringTokenizer(str, ","); 2535 int index = 0; 2536 while (tokenizer.hasMoreElements()) { 2537 String token = tokenizer.nextToken(); 2538 output[index++] = Integer.parseInt(token); 2539 } 2540 } 2541 2542 // Splits a comma delimited string to an ArrayList of Float. 2543 private void splitFloat(String str, float[] output) { 2544 if (str == null) return; 2545 2546 StringTokenizer tokenizer = new StringTokenizer(str, ","); 2547 int index = 0; 2548 while (tokenizer.hasMoreElements()) { 2549 String token = tokenizer.nextToken(); 2550 output[index++] = Float.parseFloat(token); 2551 } 2552 } 2553 2554 // Returns the value of a float parameter. 2555 private float getFloat(String key, float defaultValue) { 2556 try { 2557 return Float.parseFloat(mMap.get(key)); 2558 } catch (NumberFormatException ex) { 2559 return defaultValue; 2560 } 2561 } 2562 2563 // Returns the value of a integer parameter. 2564 private int getInt(String key, int defaultValue) { 2565 try { 2566 return Integer.parseInt(mMap.get(key)); 2567 } catch (NumberFormatException ex) { 2568 return defaultValue; 2569 } 2570 } 2571 2572 // Splits a comma delimited string to an ArrayList of Size. 2573 // Return null if the passing string is null or the size is 0. 2574 private ArrayList<Size> splitSize(String str) { 2575 if (str == null) return null; 2576 2577 StringTokenizer tokenizer = new StringTokenizer(str, ","); 2578 ArrayList<Size> sizeList = new ArrayList<Size>(); 2579 while (tokenizer.hasMoreElements()) { 2580 Size size = strToSize(tokenizer.nextToken()); 2581 if (size != null) sizeList.add(size); 2582 } 2583 if (sizeList.size() == 0) return null; 2584 return sizeList; 2585 } 2586 2587 // Parses a string (ex: "480x320") to Size object. 2588 // Return null if the passing string is null. 2589 private Size strToSize(String str) { 2590 if (str == null) return null; 2591 2592 int pos = str.indexOf('x'); 2593 if (pos != -1) { 2594 String width = str.substring(0, pos); 2595 String height = str.substring(pos + 1); 2596 return new Size(Integer.parseInt(width), 2597 Integer.parseInt(height)); 2598 } 2599 Log.e(TAG, "Invalid size parameter string=" + str); 2600 return null; 2601 } 2602 2603 // Splits a comma delimited string to an ArrayList of int array. 2604 // Example string: "(10000,26623),(10000,30000)". Return null if the 2605 // passing string is null or the size is 0. 2606 private ArrayList<int[]> splitRange(String str) { 2607 if (str == null || str.charAt(0) != '(' 2608 || str.charAt(str.length() - 1) != ')') { 2609 Log.e(TAG, "Invalid range list string=" + str); 2610 return null; 2611 } 2612 2613 ArrayList<int[]> rangeList = new ArrayList<int[]>(); 2614 int endIndex, fromIndex = 1; 2615 do { 2616 int[] range = new int[2]; 2617 endIndex = str.indexOf("),(", fromIndex); 2618 if (endIndex == -1) endIndex = str.length() - 1; 2619 splitInt(str.substring(fromIndex, endIndex), range); 2620 rangeList.add(range); 2621 fromIndex = endIndex + 3; 2622 } while (endIndex != str.length() - 1); 2623 2624 if (rangeList.size() == 0) return null; 2625 return rangeList; 2626 } 2627 }; 2628} 2629