Android-系统服务-CameraService

本文详细介绍了Android Camera API的使用方法,包括Camera权限设置、Camera API的接口调用流程及注意事项,如takePicture方法用于触发图片拍摄,openCamera方法用于打开指定ID的摄像头设备等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

0 快速索引表

  • 权限汇总

https://developer.android.google.cn/reference/android/Manifest.permission

/frameworks/base/core/res/AndroidManifest.xml

……

  • 接口汇总

https://developer.android.google.cn/reference/android/hardware/Camera

/frameworks/base/core/java/android/hardware/Camera.java

android.hardware.Camera.takePicture

https://developer.android.google.cn/reference/android/hardware/camera2/CameraManager

/frameworks/base/core/java/android/hardware/camera2/CameraManager.java

android.hardware.camera2.CameraManager.openCamera

CameraCaptureSession  |  Android Developers

/frameworks/base/core/java/android/hardware/camera2/CameraCaptureSession.java

android.hardware.camera2.CameraCaptureSession.capture

android.hardware.camera2.CameraCaptureSession.captureBurst

android.hardware.camera2.CameraCaptureSession.setRepeatingRequest

  • adb命令

adb shell cameraserver

adb shell cmd media.camera

adb shell cmd media.camera.proxy


1 需求


2 权限


3 接口

android.hardware.Camera.takePicture

1454      /**
1455       * Triggers an asynchronous image capture. The camera service will initiate
1456       * a series of callbacks to the application as the image capture progresses.
1457       * The shutter callback occurs after the image is captured. This can be used
1458       * to trigger a sound to let the user know that image has been captured. The
1459       * raw callback occurs when the raw image data is available (NOTE: the data
1460       * will be null if there is no raw image callback buffer available or the
1461       * raw image callback buffer is not large enough to hold the raw image).
1462       * The postview callback occurs when a scaled, fully processed postview
1463       * image is available (NOTE: not all hardware supports this). The jpeg
1464       * callback occurs when the compressed image is available. If the
1465       * application does not need a particular callback, a null can be passed
1466       * instead of a callback method.
1467       *
1468       * <p>This method is only valid when preview is active (after
1469       * {@link #startPreview()}).  Preview will be stopped after the image is
1470       * taken; callers must call {@link #startPreview()} again if they want to
1471       * re-start preview or take more pictures. This should not be called between
1472       * {@link android.media.MediaRecorder#start()} and
1473       * {@link android.media.MediaRecorder#stop()}.
1474       *
1475       * <p>After calling this method, you must not call {@link #startPreview()}
1476       * or take another picture until the JPEG callback has returned.
1477       *
1478       * @param shutter   the callback for image capture moment, or null
1479       * @param raw       the callback for raw (uncompressed) image data, or null
1480       * @param postview  callback with postview image data, may be null
1481       * @param jpeg      the callback for JPEG image data, or null
1482       * @throws RuntimeException if starting picture capture fails; usually this
1483       *    would be because of a hardware or other low-level error, or because
1484       *    release() has been called on this Camera instance.
1485       */
1486      public final void takePicture(ShutterCallback shutter, PictureCallback raw,
1487              PictureCallback postview, PictureCallback jpeg) {
1488          mShutterCallback = shutter;
1489          mRawImageCallback = raw;
1490          mPostviewCallback = postview;
1491          mJpegCallback = jpeg;
1492  
1493          // If callback is not set, do not send me callbacks.
1494          int msgType = 0;
1495          if (mShutterCallback != null) {
1496              msgType |= CAMERA_MSG_SHUTTER;
1497          }
1498          if (mRawImageCallback != null) {
1499              msgType |= CAMERA_MSG_RAW_IMAGE;
1500          }
1501          if (mPostviewCallback != null) {
1502              msgType |= CAMERA_MSG_POSTVIEW_FRAME;
1503          }
1504          if (mJpegCallback != null) {
1505              msgType |= CAMERA_MSG_COMPRESSED_IMAGE;
1506          }
1507  
1508          native_takePicture(msgType);
1509          mFaceDetectionRunning = false;
1510      }

android.hardware.camera2.CameraManager.openCamera

747      /**
748       * Open a connection to a camera with the given ID.
749       *
750       * <p>Use {@link #getCameraIdList} to get the list of available camera
751       * devices. Note that even if an id is listed, open may fail if the device
752       * is disconnected between the calls to {@link #getCameraIdList} and
753       * {@link #openCamera}, or if a higher-priority camera API client begins using the
754       * camera device.</p>
755       *
756       * <p>As of API level 23, devices for which the
757       * {@link AvailabilityCallback#onCameraUnavailable(String)} callback has been called due to the
758       * device being in use by a lower-priority, background camera API client can still potentially
759       * be opened by calling this method when the calling camera API client has a higher priority
760       * than the current camera API client using this device.  In general, if the top, foreground
761       * activity is running within your application process, your process will be given the highest
762       * priority when accessing the camera, and this method will succeed even if the camera device is
763       * in use by another camera API client. Any lower-priority application that loses control of the
764       * camera in this way will receive an
765       * {@link android.hardware.camera2.CameraDevice.StateCallback#onDisconnected} callback.
766       * Opening the same camera ID twice in the same application will similarly cause the
767       * {@link android.hardware.camera2.CameraDevice.StateCallback#onDisconnected} callback
768       * being fired for the {@link CameraDevice} from the first open call and all ongoing tasks
769       * being droppped.</p>
770       *
771       * <p>Once the camera is successfully opened, {@link CameraDevice.StateCallback#onOpened} will
772       * be invoked with the newly opened {@link CameraDevice}. The camera device can then be set up
773       * for operation by calling {@link CameraDevice#createCaptureSession} and
774       * {@link CameraDevice#createCaptureRequest}</p>
775       *
776       * <p>Before API level 30, when the application tries to open multiple {@link CameraDevice} of
777       * different IDs and the device does not support opening such combination, either the
778       * {@link #openCamera} will fail and throw a {@link CameraAccessException} or one or more of
779       * already opened {@link CameraDevice} will be disconnected and receive
780       * {@link android.hardware.camera2.CameraDevice.StateCallback#onDisconnected} callback. Which
781       * behavior will happen depends on the device implementation and can vary on different devices.
782       * Starting in API level 30, if the device does not support the combination of cameras being
783       * opened, it is guaranteed the {@link #openCamera} call will fail and none of existing
784       * {@link CameraDevice} will be disconnected.</p>
785       *
786       * <!--
787       * <p>Since the camera device will be opened asynchronously, any asynchronous operations done
788       * on the returned CameraDevice instance will be queued up until the device startup has
789       * completed and the callback's {@link CameraDevice.StateCallback#onOpened onOpened} method is
790       * called. The pending operations are then processed in order.</p>
791       * -->
792       * <p>If the camera becomes disconnected during initialization
793       * after this function call returns,
794       * {@link CameraDevice.StateCallback#onDisconnected} with a
795       * {@link CameraDevice} in the disconnected state (and
796       * {@link CameraDevice.StateCallback#onOpened} will be skipped).</p>
797       *
798       * <p>If opening the camera device fails, then the device callback's
799       * {@link CameraDevice.StateCallback#onError onError} method will be called, and subsequent
800       * calls on the camera device will throw a {@link CameraAccessException}.</p>
801       *
802       * @param cameraId
803       *             The unique identifier of the camera device to open
804       * @param callback
805       *             The callback which is invoked once the camera is opened
806       * @param handler
807       *             The handler on which the callback should be invoked, or
808       *             {@code null} to use the current thread's {@link android.os.Looper looper}.
809       *
810       * @throws CameraAccessException if the camera is disabled by device policy,
811       * has been disconnected, is being used by a higher-priority camera API client, or the device
812       * has reached its maximal resource and cannot open this camera device.
813       *
814       * @throws IllegalArgumentException if cameraId or the callback was null,
815       * or the cameraId does not match any currently or previously available
816       * camera device returned by {@link #getCameraIdList}.
817       *
818       * @throws SecurityException if the application does not have permission to
819       * access the camera
820       *
821       * @see #getCameraIdList
822       * @see android.app.admin.DevicePolicyManager#setCameraDisabled
823       */
824      @RequiresPermission(android.Manifest.permission.CAMERA)
825      public void openCamera(@NonNull String cameraId,
826              @NonNull final CameraDevice.StateCallback callback, @Nullable Handler handler)
827              throws CameraAccessException {
828  
829          openCameraForUid(cameraId, callback, CameraDeviceImpl.checkAndWrapHandler(handler),
830                  USE_CALLING_UID);
831      }

android.hardware.camera2.CameraCaptureSession.capture

291      /**
292       * <p>Submit a request for an image to be captured by the camera device.</p>
293       *
294       * <p>The request defines all the parameters for capturing the single image,
295       * including sensor, lens, flash, and post-processing settings.</p>
296       *
297       * <p>Each request will produce one {@link CaptureResult} and produce new frames for one or more
298       * target Surfaces, set with the CaptureRequest builder's
299       * {@link CaptureRequest.Builder#addTarget} method. The target surfaces (set with
300       * {@link CaptureRequest.Builder#addTarget}) must be a subset of the surfaces provided when this
301       * capture session was created.</p>
302       *
303       * <p>Multiple regular and reprocess requests can be in progress at once. If there are only
304       * regular requests or reprocess requests in progress, they are processed in first-in,
305       * first-out order. If there are both regular and reprocess requests in progress, regular
306       * requests are processed in first-in, first-out order and reprocess requests are processed in
307       * first-in, first-out order, respectively. However, the processing order of a regular request
308       * and a reprocess request in progress is not specified. In other words, a regular request
309       * will always be processed before regular requets that are submitted later. A reprocess request
310       * will always be processed before reprocess requests that are submitted later. However, a
311       * regular request may not be processed before reprocess requests that are submitted later.<p>
312       *
313       * <p>Requests submitted through this method have higher priority than
314       * those submitted through {@link #setRepeatingRequest} or
315       * {@link #setRepeatingBurst}, and will be processed as soon as the current
316       * repeat/repeatBurst processing completes.</p>
317       *
318       * <p>All capture sessions can be used for capturing images from the camera but only capture
319       * sessions created by
320       * {@link CameraDevice#createReprocessableCaptureSession createReprocessableCaptureSession}
321       * can submit reprocess capture requests. Submitting a reprocess request to a regular capture
322       * session will result in an {@link IllegalArgumentException}.</p>
323       *
324       * <p>Submitting a request that targets Surfaces with an unsupported dynamic range combination
325       * will result in an {@link IllegalArgumentException}.</p>
326       *
327       * @param request the settings for this capture
328       * @param listener The callback object to notify once this request has been
329       * processed. If null, no metadata will be produced for this capture,
330       * although image data will still be produced.
331       * @param handler the handler on which the listener should be invoked, or
332       * {@code null} to use the current thread's {@link android.os.Looper
333       * looper}.
334       *
335       * @return int A unique capture sequence ID used by
336       *             {@link CaptureCallback#onCaptureSequenceCompleted}.
337       *
338       * @throws CameraAccessException if the camera device is no longer connected or has
339       *                               encountered a fatal error
340       * @throws IllegalStateException if this session is no longer active, either because the session
341       *                               was explicitly closed, a new session has been created
342       *                               or the camera device has been closed.
343       * @throws IllegalArgumentException if the request targets no Surfaces or Surfaces that are not
344       *                                  configured as outputs for this session; or the request
345       *                                  targets a set of Surfaces that cannot be submitted
346       *                                  simultaneously in a reprocessable capture session; or a
347       *                                  reprocess capture request is submitted in a
348       *                                  non-reprocessable capture session; or the reprocess capture
349       *                                  request was created with a {@link TotalCaptureResult} from
350       *                                  a different session; or the capture targets a Surface in
351       *                                  the middle of being {@link #prepare prepared}; or the
352       *                                  handler is null, the listener is not null, and the calling
353       *                                  thread has no looper; or the request targets Surfaces with
354       *                                  an unsupported dynamic range combination
355       *
356       * @see #captureBurst
357       * @see #setRepeatingRequest
358       * @see #setRepeatingBurst
359       * @see #abortCaptures
360       * @see CameraDevice#createReprocessableCaptureSession
361       * @see android.hardware.camera2.params.DynamicRangeProfiles#getProfileCaptureRequestConstraints
362       */
363      public abstract int capture(@NonNull CaptureRequest request,
364              @Nullable CaptureCallback listener, @Nullable Handler handler)
365              throws CameraAccessException;

android.hardware.camera2.CameraCaptureSession.captureBurst

414      /**
415       * Submit a list of requests to be captured in sequence as a burst. The
416       * burst will be captured in the minimum amount of time possible, and will
417       * not be interleaved with requests submitted by other capture or repeat
418       * calls.
419       *
420       * <p>Regular and reprocess requests can be mixed together in a single burst. Regular requests
421       * will be captured in order and reprocess requests will be processed in order, respectively.
422       * However, the processing order between a regular request and a reprocess request is not
423       * specified. Each capture produces one {@link CaptureResult} and image buffers for one or more
424       * target {@link android.view.Surface surfaces}. The target surfaces (set with
425       * {@link CaptureRequest.Builder#addTarget}) must be a subset of the surfaces provided when
426       * this capture session was created.</p>
427       *
428       * <p>The main difference between this method and simply calling
429       * {@link #capture} repeatedly is that this method guarantees that no
430       * other requests will be interspersed with the burst.</p>
431       *
432       * <p>All capture sessions can be used for capturing images from the camera but only capture
433       * sessions created by
434       * {@link CameraDevice#createReprocessableCaptureSession createReprocessableCaptureSession}
435       * can submit reprocess capture requests. Submitting a reprocess request to a regular
436       * capture session will result in an {@link IllegalArgumentException}.</p>
437       *
438       * <p>Submitting a request that targets Surfaces with an unsupported dynamic range combination
439       * will result in an {@link IllegalArgumentException}.</p>
440       *
441       * @param requests the list of settings for this burst capture
442       * @param listener The callback object to notify each time one of the
443       * requests in the burst has been processed. If null, no metadata will be
444       * produced for any requests in this burst, although image data will still
445       * be produced.
446       * @param handler the handler on which the listener should be invoked, or
447       * {@code null} to use the current thread's {@link android.os.Looper
448       * looper}.
449       *
450       * @return int A unique capture sequence ID used by
451       *             {@link CaptureCallback#onCaptureSequenceCompleted}.
452       *
453       * @throws CameraAccessException if the camera device is no longer connected or has
454       *                               encountered a fatal error
455       * @throws IllegalStateException if this session is no longer active, either because the session
456       *                               was explicitly closed, a new session has been created
457       *                               or the camera device has been closed.
458       * @throws IllegalArgumentException If the requests target no Surfaces, or the requests target
459       *                                  Surfaces not currently configured as outputs; or one of the
460       *                                  requests targets a set of Surfaces that cannot be submitted
461       *                                  simultaneously in a reprocessable capture session; or a
462       *                                  reprocess capture request is submitted in a
463       *                                  non-reprocessable capture session; or one of the reprocess
464       *                                  capture requests was created with a
465       *                                  {@link TotalCaptureResult} from a different session; or one
466       *                                  of the captures targets a Surface in the middle of being
467       *                                  {@link #prepare prepared}; or if the handler is null, the
468       *                                  listener is not null, and the calling thread has no looper;
469       *                                  or the request targets Surfaces with an unsupported dynamic
470       *                                  range combination.
471       *
472       * @see #capture
473       * @see #setRepeatingRequest
474       * @see #setRepeatingBurst
475       * @see #abortCaptures
476       * @see android.hardware.camera2.params.DynamicRangeProfiles#getProfileCaptureRequestConstraints
477       */
478      public abstract int captureBurst(@NonNull List<CaptureRequest> requests,
479              @Nullable CaptureCallback listener, @Nullable Handler handler)
480              throws CameraAccessException;

android.hardware.camera2.CameraCaptureSession.setRepeatingRequest

532      /**
533       * Request endlessly repeating capture of images by this capture session.
534       *
535       * <p>With this method, the camera device will continually capture images
536       * using the settings in the provided {@link CaptureRequest}, at the maximum
537       * rate possible.</p>
538       *
539       * <p>Repeating requests are a simple way for an application to maintain a
540       * preview or other continuous stream of frames, without having to
541       * continually submit identical requests through {@link #capture}.</p>
542       *
543       * <p>Repeat requests have lower priority than those submitted
544       * through {@link #capture} or {@link #captureBurst}, so if
545       * {@link #capture} is called when a repeating request is active, the
546       * capture request will be processed before any further repeating
547       * requests are processed.<p>
548       *
549       * <p>To stop the repeating capture, call {@link #stopRepeating}. Calling
550       * {@link #abortCaptures} will also clear the request.</p>
551       *
552       * <p>Calling this method will replace any earlier repeating request or
553       * burst set up by this method or {@link #setRepeatingBurst}, although any
554       * in-progress burst will be completed before the new repeat request will be
555       * used.</p>
556       *
557       * <p>This method does not support reprocess capture requests because each reprocess
558       * {@link CaptureRequest} must be created from the {@link TotalCaptureResult} that matches
559       * the input image to be reprocessed. This is either the {@link TotalCaptureResult} of capture
560       * that is sent for reprocessing, or one of the {@link TotalCaptureResult TotalCaptureResults}
561       * of a set of captures, when data from the whole set is combined by the application into a
562       * single reprocess input image. The request must be capturing images from the camera. If a
563       * reprocess capture request is submitted, this method will throw IllegalArgumentException.</p>
564       *
565       * <p>Submitting a request that targets Surfaces with an unsupported dynamic range combination
566       * will result in an {@link IllegalArgumentException}.</p>
567       *
568       * @param request the request to repeat indefinitely
569       * @param listener The callback object to notify every time the
570       * request finishes processing. If null, no metadata will be
571       * produced for this stream of requests, although image data will
572       * still be produced.
573       * @param handler the handler on which the listener should be invoked, or
574       * {@code null} to use the current thread's {@link android.os.Looper
575       * looper}.
576       *
577       * @return int A unique capture sequence ID used by
578       *             {@link CaptureCallback#onCaptureSequenceCompleted}.
579       *
580       * @throws CameraAccessException if the camera device is no longer connected or has
581       *                               encountered a fatal error
582       * @throws IllegalStateException if this session is no longer active, either because the session
583       *                               was explicitly closed, a new session has been created
584       *                               or the camera device has been closed.
585       * @throws IllegalArgumentException If the request references no Surfaces or references Surfaces
586       *                                  that are not currently configured as outputs; or the request
587       *                                  is a reprocess capture request; or the capture targets a
588       *                                  Surface in the middle of being {@link #prepare prepared}; or
589       *                                  the handler is null, the listener is not null, and the
590       *                                  calling thread has no looper; or no requests were passed in;
591       *                                  or the request targets Surfaces with an unsupported dynamic
592       *                                  range combination.
593       *
594       * @see #capture
595       * @see #captureBurst
596       * @see #setRepeatingBurst
597       * @see #stopRepeating
598       * @see #abortCaptures
599       * @see android.hardware.camera2.params.DynamicRangeProfiles#getProfileCaptureRequestConstraints
600       */
601      public abstract int setRepeatingRequest(@NonNull CaptureRequest request,
602              @Nullable CaptureCallback listener, @Nullable Handler handler)
603              throws CameraAccessException;


4 示例


5 adb

  • adb shell cameraserver

  • adb shell cmd media.camer
C:\>adb shell cmd media.camera help
Camera service commands:
  get-uid-state <PACKAGE> [--user USER_ID] gets the uid state
  set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state
  reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override
  set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat
      Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override
  get-rotate-and-crop returns the current override rotate-and-crop value
  set-image-dump-mask <MASK> specifies the formats to be saved to disk
      Valid values 0=OFF, 1=ON for JPEG
  get-image-dump-mask returns the current image-dump-mask value
  set-camera-mute <0/1> enable or disable camera muting
  watch <start|stop|dump|print|clear> manages tag monitoring in connected clients
  help print this message
  • adb shell cmd media.camera.proxy help


6 参考资料(其它)

Android Camera了解一下_渡口一艘船的博客-CSDN博客_android camera

Android之camera1和2的简单使用_androidcamera1和camera2的区别

Android Camera2 API和拍照与录像过程_新根的博客-CSDN博客

android 实现拍照的2种方法_napolun007的专栏-CSDN博客_android实现拍照

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值