Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
Примечание. Эта страница относится к пакету Camera2 . Если вашему приложению не требуются специальные низкоуровневые функции Camera2, мы рекомендуем использовать CameraX . И CameraX, и Camera2 поддерживают Android 5.0 (уровень API 21) и выше.
Camera2 предоставляет API расширений для доступа к расширениям , которые производители устройств реализовали на различных устройствах Android. Список поддерживаемых режимов расширений см. в разделе Расширения камеры .
На следующем изображении показана архитектура расширений камеры.
Рисунок 1. Архитектура расширений камер
Приложение Camera2 может использовать расширения через API Camera2. API Camera2 предоставляет способы запроса доступных расширений, настройки сеанса дополнительной камеры и взаимодействия с OEM-библиотекой расширений камеры. Это позволяет вашему приложению использовать такие расширения, как «Ночь», «HDR», «Авто», «Боке» или «Ретушь лица».
Проверьте устройство камеры на совместимость API расширений Camera2.
Следующий фрагмент кода проверяет, поддерживает ли устройство API расширений Camera2. Расширения поддерживаются не всеми устройствами, либо устройство может поддерживать часть расширений. Фрагмент возвращает список совместимых идентификаторов камер, которые поддерживают расширения камер.
Создайте сеанс CameraExtensionSession с помощью API расширений Camera2.
API расширений Camera2 при использовании с совместимыми устройствами позволяет получить доступ к определенным расширениям камеры. В следующем фрагменте кода показан пример создания CameraExtensionSession для использования режима ночной съемки для существующего приложения Camera2.
Котлин
privatevalcaptureCallbacks=object:CameraExtensionSession.ExtensionCaptureCallback(){// Implement Capture Callbacks}privatevalextensionSessionStateCallback=object:CameraExtensionSession.StateCallback(){overridefunonConfigured(session:CameraExtensionSession){cameraExtensionSession=sessiontry{valcaptureRequest=cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW).apply{addTarget(previewSurface)}.build()session.setRepeatingRequest(captureRequest,Dispatchers.IO.asExecutor(),captureCallbacks)}catch(e:CameraAccessException){Snackbar.make(previewView,"Failed to preview capture request",Snackbar.LENGTH_SHORT).show()requireActivity().finish()}}overridefunonClosed(session:CameraExtensionSession){super.onClosed(session)cameraDevice.close()}overridefunonConfigureFailed(session:CameraExtensionSession){Snackbar.make(previewView,"Failed to start camera extension preview",Snackbar.LENGTH_SHORT).show()requireActivity().finish()}}privatefunstartExtensionSession(){valoutputConfig=arrayListOf(OutputConfiguration(stillImageReader.surface),OutputConfiguration(previewSurface))valextensionConfiguration=ExtensionSessionConfiguration(CameraExtensionCharacteristics.EXTENSION_NIGHT,outputConfig,Dispatchers.IO.asExecutor(),extensionSessionStateCallback)cameraDevice.createExtensionSession(extensionConfiguration)}
Ява
privateCameraExtensionSession.ExtensionCaptureCallbackcaptureCallbacks=newCameraExtensionSession.ExtensionCaptureCallback(){// Implement Capture Callbacks};privateCameraExtensionSession.StateCallbackextensionSessionStateCallback=newCameraExtensionSession.StateCallback(){@OverridepublicvoidonConfigured(@NonNullCameraExtensionSessionsession){cameraExtensionSession=session;try{CaptureRequest.BuildercaptureRequestBuilder=cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);captureRequestBuilder.addTarget(previewSurface);CaptureRequestcaptureRequest=captureRequestBuilder.build();session.setRepeatingRequest(captureRequest,backgroundExecutor,captureCallbacks);}catch(CameraAccessExceptione){Snackbar.make(previewView,"Failed to preview capture request",Snackbar.LENGTH_SHORT).show();requireActivity().finish();}}@OverridepublicvoidonClosed(@NonNullCameraExtensionSessionsession){super.onClosed(session);cameraDevice.close();}@OverridepublicvoidonConfigureFailed(@NonNullCameraExtensionSessionsession){Snackbar.make(previewView,"Failed to start camera extension preview",Snackbar.LENGTH_SHORT).show();requireActivity().finish();}};privatevoidstartExtensionSession(){ArrayList<OutputConfiguration>outputConfig=newArrayList<>();outputConfig.add(newOutputConfiguration(stillImageReader.getSurface()));outputConfig.add(newOutputConfiguration(previewSurface));ExtensionSessionConfigurationextensionConfiguration=newExtensionSessionConfiguration(CameraExtensionCharacteristics.EXTENSION_NIGHT,outputConfig,backgroundExecutor,extensionSessionStateCallback);}
Контент и образцы кода на этой странице предоставлены по лицензиям. Java и OpenJDK – это зарегистрированные товарные знаки корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2025-07-29 UTC.
[[["Прост для понимания","easyToUnderstand","thumb-up"],["Помог мне решить мою проблему","solvedMyProblem","thumb-up"],["Другое","otherUp","thumb-up"]],[["Отсутствует нужная мне информация","missingTheInformationINeed","thumb-down"],["Слишком сложен/слишком много шагов","tooComplicatedTooManySteps","thumb-down"],["Устарел","outOfDate","thumb-down"],["Проблема с переводом текста","translationIssue","thumb-down"],["Проблемы образцов/кода","samplesCodeIssue","thumb-down"],["Другое","otherDown","thumb-down"]],["Последнее обновление: 2025-07-29 UTC."],[],[],null,["# Camera2 Extensions API\n\n**Note:** This page refers to the [Camera2](/reference/android/hardware/camera2/package-summary) package. Unless your app requires specific, low-level features from Camera2, we recommend using [CameraX](/camerax). Both CameraX and Camera2 support Android 5.0 (API level 21) and higher.\n\n\u003cbr /\u003e\n\nCamera2 provides an Extensions API for accessing [extensions](/training/camera/camera-extensions) that device manufacturers have implemented on various Android devices. For a list of supported extension modes, see [Camera extensions](/training/camera/camera-extensions).\n\nFor a list of devices that support extensions, see [Supported devices](/training/camera/supported-devices).\n\nExtensions architecture\n-----------------------\n\nThe following image shows the camera extensions architecture.\n**Figure 1.**Camera Extensions architecture\n\nA Camera2 application can use extensions through the Camera2 API. The Camera2\nAPI provides ways to query for available extensions, configure an extension\ncamera session, and communicate with the Camera Extensions OEM library. This\nallows your application to use extensions like Night, HDR, Auto, Bokeh, or\nFace Retouch.\n\nTest a camera device for Camera2 Extensions API compatibility\n-------------------------------------------------------------\n\nThe following code snippet checks if the device supports the Camera2\nExtensions API. Extensions are not supported by all devices or the device might support a subset\nof extensions. The snippet returns a list of compatible camera IDs which support\ncamera extensions. \n\n### Kotlin\n\n```kotlin\nprivate fun getExtensionCameraIds(cameraManager: CameraManager): List\u003cString\u003e =\n if (Build.VERSION.SDK_INT \u003e= Build.VERSION_CODES.S) {\n cameraManager.cameraIdList.filter { cameraId -\u003e\n val characteristics = cameraManager.getCameraCharacteristics(cameraId)\n val extensionCharacteristics =\n cameraManager.getCameraExtensionCharacteristics(cameraId)\n val capabilities =\n characteristics.get(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES)\n extensionCharacteristics.supportedExtensions.isNotEmpty() &&\n capabilities?.contains(\n CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE\n ) ?: false\n }\n } else emptyList()\n```\n\n### Java\n\n```java\nprivate List\u003cString\u003e getExtensionCameraIds(CameraManager cameraManager)\n throws CameraAccessException {\n if (Build.VERSION.SDK_INT \u003e= Build.VERSION_CODES.S) {\n return Arrays.stream(cameraManager.getCameraIdList()).filter(cameraId -\u003e {\n try {\n CameraCharacteristics characteristics =\n cameraManager.getCameraCharacteristics(cameraId);\n CameraExtensionCharacteristics extensionCharacteristics =\n cameraManager.getCameraExtensionCharacteristics(cameraId);\n IntStream capabilities =\n Arrays.stream(\n characteristics.get(\n CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES\n )\n );\n return !extensionCharacteristics.getSupportedExtensions().isEmpty() &&\n capabilities.anyMatch(capability -\u003e capability == CameraCharacteristics\n .REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE\n );\n } catch (CameraAccessException e) {\n throw new RuntimeException(e);\n }\n }).collect(Collectors.toList());\n } else {\n return Collections.emptyList();\n }\n}\n```\n\nCreate a CameraExtensionSession with the Camera2 Extensions API\n---------------------------------------------------------------\n\nThe Camera2 Extensions API, when used with compatible devices, lets you access\ncertain camera extensions. The following code snippet showcases an example of\nhow to create a [`CameraExtensionSession`](https://developer.android.com/reference/android/hardware/camera2/CameraExtensionSession)\nfor using night capture mode for an existing Camera2 application. \n\n### Kotlin\n\n```kotlin\nprivate val captureCallbacks = object : CameraExtensionSession.ExtensionCaptureCallback() {\n // Implement Capture Callbacks\n}\nprivate val extensionSessionStateCallback = object : CameraExtensionSession.StateCallback() {\n override fun onConfigured(session: CameraExtensionSession) {\n cameraExtensionSession = session\n try {\n val captureRequest =\n cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW).apply {\n addTarget(previewSurface)\n }.build()\n session.setRepeatingRequest(\n captureRequest,\n Dispatchers.IO.asExecutor(),\n captureCallbacks\n )\n } catch (e: CameraAccessException) {\n Snackbar.make(\n previewView,\n \"Failed to preview capture request\",\n Snackbar.LENGTH_SHORT\n ).show()\n requireActivity().finish()\n }\n }\n\n override fun onClosed(session: CameraExtensionSession) {\n super.onClosed(session)\n cameraDevice.close()\n }\n\n override fun onConfigureFailed(session: CameraExtensionSession) {\n Snackbar.make(\n previewView,\n \"Failed to start camera extension preview\",\n Snackbar.LENGTH_SHORT\n ).show()\n requireActivity().finish()\n }\n}\n\nprivate fun startExtensionSession() {\n val outputConfig = arrayListOf(\n OutputConfiguration(stillImageReader.surface),\n OutputConfiguration(previewSurface)\n )\n val extensionConfiguration = ExtensionSessionConfiguration(\n CameraExtensionCharacteristics.EXTENSION_NIGHT,\n outputConfig,\n Dispatchers.IO.asExecutor(),\n extensionSessionStateCallback\n )\n cameraDevice.createExtensionSession(extensionConfiguration)\n}\n```\n\n### Java\n\n```java\nprivate CameraExtensionSession.ExtensionCaptureCallback captureCallbacks =\n new CameraExtensionSession.ExtensionCaptureCallback() {\n // Implement Capture Callbacks\n };\n\nprivate CameraExtensionSession.StateCallback extensionSessionStateCallback =\n new CameraExtensionSession.StateCallback() {\n @Override\n public void onConfigured(@NonNull CameraExtensionSession session) {\n cameraExtensionSession = session;\n try {\n CaptureRequest.Builder captureRequestBuilder =\n cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);\n captureRequestBuilder.addTarget(previewSurface);\n CaptureRequest captureRequest = captureRequestBuilder.build();\n session.setRepeatingRequest(captureRequest, backgroundExecutor, captureCallbacks);\n } catch (CameraAccessException e) {\n Snackbar.make(\n previewView,\n \"Failed to preview capture request\",\n Snackbar.LENGTH_SHORT\n ).show();\n requireActivity().finish();\n }\n }\n\n @Override\n public void onClosed(@NonNull CameraExtensionSession session) {\n super.onClosed(session);\n cameraDevice.close();\n }\n\n @Override\n public void onConfigureFailed(@NonNull CameraExtensionSession session) {\n Snackbar.make(\n previewView,\n \"Failed to start camera extension preview\",\n Snackbar.LENGTH_SHORT\n ).show();\n requireActivity().finish();\n }\n };\n\nprivate void startExtensionSession() {\n ArrayList\u003cOutputConfiguration\u003e outputConfig = new ArrayList\u003c\u003e();\n outputConfig.add(new OutputConfiguration(stillImageReader.getSurface()));\n outputConfig.add(new OutputConfiguration(previewSurface));\n ExtensionSessionConfiguration extensionConfiguration = new ExtensionSessionConfiguration(\n CameraExtensionCharacteristics.EXTENSION_NIGHT,\n outputConfig,\n backgroundExecutor,\n extensionSessionStateCallback\n );\n}\n```\n\nAdditional resources\n--------------------\n\nFor more information, see\n[`CameraExtensionCharacteristics`](/reference/android/hardware/camera2/CameraExtensionCharacteristics)\nand view the public [Camera2 Extensions API samples](https://github.com/android/camera-samples/tree/master/Camera2Extensions)\nfor more."]]