请求并获得必要权限后,您的应用便可以访问无屏眼镜或带屏眼镜上的硬件。访问眼镜硬件(而非手机硬件)的关键在于使用投影上下文。
获取投影上下文主要有两种方式,具体取决于代码的执行位置:
如果您的代码在投射 activity 中运行,请获取投射上下文
如果应用的代码在投射的 activity 中运行,则其自身的 activity 上下文已经是投射的上下文。在这种情况下,在该 activity 中发出的调用已经可以访问眼镜的硬件。
获取在“电话”应用组件中运行的代码的投影上下文
如果应用中投影 activity 之外的部分(例如手机 activity 或服务)需要访问眼镜的硬件,则必须明确获取投影上下文。为此,请使用 createProjectedDeviceContext 方法:
@RequiresApi(Build.VERSION_CODES.BAKLAVA) @OptIn(ExperimentalProjectedApi::class, ExperimentalCoroutinesApi::class) fun monitorProjectedDeviceConnectivity( context: Context, onConnected: suspend (projectedContext: Context) -> (() -> Unit)? ) { val lifecycleScope = (context as? LifecycleOwner)?.lifecycleScope ?: CoroutineScope(Dispatchers.Main + SupervisorJob()) lifecycleScope.launch { var cleanupAction: (() -> Unit)? = null try { // Before creating a projected context, verify that the projected device // is connected to the host device (phone). // While this flow collects true, the active projected context remains valid. ProjectedContext.isProjectedDeviceConnected(context, coroutineContext) .distinctUntilChanged() .collectLatest { isConnected -> // Clean up any previous session resources prior to state transitions. cleanupAction?.invoke() cleanupAction = null if (!isConnected) { Log.i(TAG, "Projected device disconnected. Cleaning up hardware resources...") return@collectLatest } // Inside a phone Activity or Service, create a projected context. // Note: If you are already inside a projected Activity, the default context // is already a projected context. val projectedContext = runCatching { ProjectedContext.createProjectedDeviceContext(context) }.onFailure { e -> Log.e(TAG, "Failed to create projected context", e) }.getOrNull() ?: return@collectLatest // Use the new, valid `projectedContext` to initialize system services (e.g., CameraManager). Log.i(TAG, "Projected device connected. Initializing hardware...") cleanupAction = onConnected(projectedContext) } } finally { // Guarantee final resource cleanup on Activity destruction or scope cancellation. cleanupAction?.invoke() cleanupAction = null } } }
检查有效性
将 createProjectedDeviceContext 调用封装在 ProjectedContext.isProjectedDeviceConnected 中。当此方法返回 true 时,投影上下文对已连接的设备仍然有效,并且您的“电话”应用 activity 或服务(例如 CameraManager)可以访问眼镜硬件。
断开连接时清理
投影上下文与已连接设备的生命周期相关联,因此会在设备断开连接时销毁。当设备断开连接时,ProjectedContext.isProjectedDeviceConnected 会返回 false。您的应用应监听此更改,并清理应用使用该投影上下文创建的所有系统服务(例如 CameraManager)或资源。
重新连接时重新初始化
当眼镜重新连接时,您的应用可以使用 createProjectedDeviceContext 获取另一个投影上下文实例,然后使用新的投影上下文重新初始化任何系统服务或资源。
使用眼镜的麦克风录制音频
您可以使用蓝牙免触摸配置文件 (HFP) 通过眼镜录制音频。 在此模式下,眼镜会使用标准耳机和高级音频分发配置文件 (A2DP) 配置文件连接到手机,其功能类似于典型的蓝牙外围设备。如果您的应用已设计为支持标准蓝牙录音,则您可以使用此方法从眼镜录制音频,而无需进行任何额外开发。
使用蓝牙 HFP 录制音频
如需使用蓝牙 HFP 录制音频,请先请求所需的运行时权限,然后使用 AudioManager API 录制音频,如以下部分所述。
请求权限
与任何标准蓝牙音频设备一样,RECORD_AUDIO、BLUETOOTH_CONNECT 和其他相关权限由手机控制,而不是由已连接的设备(例如无屏眼镜或带屏眼镜)控制。
请按照以下步骤请求权限:
在应用的清单文件中声明以下权限:
使用标准 Android 权限流程在运行时请求
RECORD_AUDIO和BLUETOOTH_CONNECT权限。
使用 AudioManager 路由音频
在用户向您的应用授予必要的运行时权限后,请使用 AudioManager API 将通信设备设置为 TYPE_BLUETOOTH_SCO,以便通过蓝牙 HFP 路由音频。这会指示系统从蓝牙外围设备检索音频。
val audioManager = context.getSystemService(AudioManager::class.java) ?: return val hfpDevice = audioManager.availableCommunicationDevices .firstOrNull { it.type == AudioDeviceInfo.TYPE_BLUETOOTH_SCO } ?: return // HFP input is limited to 16 kHz, with mono or stereo channel configurations. val sampleRate = 16_000 val channelMask = AudioFormat.CHANNEL_IN_MONO val encoding = AudioFormat.ENCODING_PCM_16BIT // Use a small multiple of the minimum buffer size to keep chunks short for low latency. val minBufferSize = AudioRecord.getMinBufferSize(sampleRate, channelMask, encoding) if (minBufferSize <= 0) return val audioRecord = AudioRecord.Builder() .setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION) .setAudioFormat( AudioFormat.Builder() .setSampleRate(sampleRate) .setChannelMask(channelMask) .setEncoding(encoding) .build() ) .setBufferSizeInBytes(minBufferSize * 2) .build() try { // Route voice communication audio through the Bluetooth device. if (!audioManager.setCommunicationDevice(hfpDevice)) return audioRecord.startRecording() // Read audio with audioRecord.read() on a background thread. } finally { // Stop and release when done. if (audioRecord.recordingState == AudioRecord.RECORDSTATE_RECORDING) audioRecord.stop() audioRecord.release() audioManager.clearCommunicationDevice() }
使用眼镜的摄像头拍摄图片
如需使用眼镜的摄像头拍摄图片,请使用 monitorProjectedDeviceConnectivity 监控连接性,以获取投影的设备上下文,创建绑定到该上下文的隔离 LifecycleCameraProvider,监听摄像头是否存在,并绑定 CameraX 的 ImageCapture 用例。
首先,监控设备连接情况,并使用单流 CameraXConfig.Builder 初始化 LifecycleCameraProvider.createInstance:
@OptIn(ExperimentalCameraProviderConfiguration::class) @RequiresApi(Build.VERSION_CODES.BAKLAVA) @SuppressLint("RestrictedApi") fun setUpGlassesCamera(activity: ComponentActivity) { monitorProjectedDeviceConnectivity(activity) { projectedContext -> val cameraManager = projectedContext.getSystemService(CameraManager::class.java) ?: run { Log.e(TAG, "CameraManager not available on projected context") return@monitorProjectedDeviceConnectivity null } // `setRepeatingStreamForced()` is currently internal but will be public soon. val cameraConfig = CameraXConfig.Builder .fromConfig(Camera2Config.defaultConfig()) .setRepeatingStreamForced(false) .build() val cameraProvider = try { // Acquire CameraX provider specifically bound to the projected context. // If the device disconnects while suspending, collectLatest cancels this coroutine. LifecycleCameraProvider.createInstance(projectedContext, cameraConfig) } catch (e: IllegalStateException) { Log.e(TAG, "Failed to initialize projected camera services", e) return@monitorProjectedDeviceConnectivity null } // Set up the listener to react to camera availability changes asynchronously. val availabilityCallback = registerAvailabilityListener( cameraManager = cameraManager, cameraProvider = cameraProvider, executor = ContextCompat.getMainExecutor(activity), onCameraAvailable = { cameraId -> // Delegate camera selection, resolution querying, and use-case binding. bindGlassesImageCapture(cameraProvider, cameraId, activity) } ) // Return a clean-up closure invoked automatically by monitorProjectedDeviceConnectivity // on disconnect, coroutine cancellation, or Activity destruction. return@monitorProjectedDeviceConnectivity { Log.i(TAG, "Projected camera setup scope ended. Tearing down resources...") try { cameraManager.unregisterAvailabilityCallback(availabilityCallback) } finally { cameraProvider.unbindAll() } } } }
在 CameraX 1.6.0 及更高版本中,使用 addCameraPresenceListener 注册 CameraPresenceListener,以便在添加或移除眼镜的摄像头时做出响应:
@OptIn(ExperimentalCameraProviderConfiguration::class) fun registerAvailabilityListener( cameraManager: CameraManager, cameraProvider: LifecycleCameraProvider, executor: Executor, onCameraAvailable: (cameraId: String) -> Unit ): CameraManager.AvailabilityCallback { val callback = object : CameraManager.AvailabilityCallback() { override fun onCameraAvailable(cameraId: String) { super.onCameraAvailable(cameraId) Log.i(TAG, "Glasses camera available (ID: $cameraId). Binding use case...") // Fires only after the OS finishes re-registering the glasses' camera. // Pass the fresh cameraId directly—never cache it, as it may change when recreated. onCameraAvailable(cameraId) } override fun onCameraUnavailable(cameraId: String) { super.onCameraUnavailable(cameraId) Log.i(TAG, "Glasses camera unavailable (ID: $cameraId). Releasing resources...") // Gracefully release the pipeline when the projected camera becomes unavailable. cameraProvider.unbindAll() } } cameraManager.registerAvailabilityCallback(executor, callback) return callback }
接下来,使用监听器提供的 CameraIdentifier 从 availableCameraInfos 中选择眼镜的摄像头,并绑定 ImageCapture:
/** * Selects the projected camera matching dynamic [cameraId] from * [LifecycleCameraProvider.availableCameraInfos], verifies availability, and binds an * [ImageCapture] use case targeting a 16:9 resolution to [lifecycleOwner]. * * Note: Depending on your application's needs, [ImageCapture] can be swapped out for other * standard CameraX use cases: * - Use [ImageAnalysis] for real-time streaming workloads (e.g., OCR, AI vision, or VPS). * - Use [VideoCapture] for video recording pipelines. */ @OptIn(ExperimentalCamera2Interop::class, ExperimentalCameraProviderConfiguration::class) fun bindGlassesImageCapture( cameraProvider: LifecycleCameraProvider, cameraId: String, lifecycleOwner: LifecycleOwner, preferredResolution: Size = Size(1920, 1080) ): ImageCapture? { return try { // Discover available cameras dynamically via `availableCameraInfos` // Narrow it down by the dynamic `cameraId` because the projected camera's ID may // change when recreated val cameraInfo = cameraProvider.availableCameraInfos.firstOrNull { info -> Camera2CameraInfo.from(info).cameraId == cameraId } // Pre-binding check: Verify the selected camera is registered and available on the device. // The projected camera may be unavailable (for example, if the user took off the glasses). if (cameraInfo == null) { Log.w(TAG, "Glasses camera (ID: $cameraId) is not currently available.") return null } val cameraSelector = cameraInfo.cameraSelector val resolutionSelector = ResolutionSelector.Builder() .setAspectRatioStrategy(AspectRatioStrategy.RATIO_16_9_FALLBACK_AUTO_STRATEGY) .setResolutionStrategy( ResolutionStrategy( preferredResolution, ResolutionStrategy.FALLBACK_RULE_CLOSEST_LOWER ) ) .build() // Initialize the ImageCapture use case. val imageCapture = ImageCapture.Builder() .setResolutionSelector(resolutionSelector) .build() // Unbind any previously bound use cases before rebinding to the lifecycle owner. cameraProvider.unbindAll() // Bind the configured use case. You can swap `imageCapture` out for an `ImageAnalysis` // (e.g., from `setupCameraStreamingFps`) or `VideoCapture` instance here to match your use case. // `bindToLifecycle()` can throw IllegalArgumentException if use cases // are incompatible, or IllegalStateException if the LifecycleOwner is destroyed. cameraProvider.bindToLifecycle( lifecycleOwner, cameraSelector, imageCapture ) Log.i(TAG, "ImageCapture successfully bound for camera ID $cameraId") imageCapture } catch (exc: CameraInfoUnavailableException) { Log.e(TAG, "Unable to access camera info for ID $cameraId", exc) null } catch (exc: IllegalArgumentException) { Log.e(TAG, "Invalid camera configuration or use case combination for ID $cameraId", exc) null } catch (exc: IllegalStateException) { Log.e(TAG, "Camera is already bound to another lifecycle or closed", exc) null } }
代码要点
- 每个设备
LifecycleCameraProvider:使用LifecycleCameraProvider.createInstance创建一个限定于活跃投影上下文的隔离摄像头提供程序。由于当眼镜断开连接并重新连接时,投影上下文的deviceId可能会发生变化,而应用进程会保持活动状态,因此创建每个设备的提供程序可确保 CameraX 绑定到处于活动状态的已连接设备。 - 监听摄像头是否存在:在 CameraX 1.6.0 及更高版本中,使用
cameraProvider.addCameraPresenceListener注册CameraPresenceListener,而不是在眼镜连接时立即打开摄像头。眼镜和主机之间的异步设置必须在操作系统完成眼镜摄像头重新创建之前完成,并且眼镜摄像头也可能在连接时动态消失(例如在热缓解期间)。- 添加摄像头 (
onCamerasAdded):在availableCameraInfos更新为包含添加的摄像头后触发,从而避免在设置期间出现时间争用。 - 移除摄像头 (
onCamerasRemoved):跟踪摄像头是否存在,而不是其使用状态,因此在此处解除绑定仅会在眼镜的摄像头被移除时释放资源,而不是在您自己的应用打开摄像头时做出反应。
- 添加摄像头 (
- 断开连接时清理:当眼镜断开连接或 activity 被销毁时,返回到
monitorProjectedDeviceConnectivity的清理闭包会调用removeCameraPresenceListener和unbindAll()。 - 动态摄像头选择:使用
isOf将传递给onCamerasAdded的CameraIdentifier与availableCameraInfos进行匹配,以动态选择眼镜的摄像头。 - 自定义分辨率:构建一个
ResolutionSelector,以示例 16:9 宽高比和您首选的分辨率(回退到最接近的较低受支持大小)为目标,用于ImageCapture。支持的宽高比和分辨率因眼镜设备和模式而异(例如 4:3 和 16:9),因此如果您需要检查确切支持的尺寸,请查询StreamConfigurationMap。 - 生命周期绑定:将
ImageCapture绑定到LifecycleOwner,从而根据 activity 的生命周期自动管理相机打开和关闭转换。 - 针对单流硬件进行配置:眼镜的摄像头流水线一次只能有一个活跃流。单独绑定
ImageCapture时,CameraX 默认会附加一个内部重复流 (MeteringRepeating) 用于对焦和测光,这会导致单流处理流水线停滞。在传递给LifecycleCameraProvider.createInstance的CameraXConfig中传递setRepeatingStreamForced(false),以便ImageCapture可以在没有预览流的情况下进行绑定。
设置好眼镜的摄像头后,您可以使用 CameraX 的 ImageCapture 类拍摄图片。如需了解如何使用 takePicture 拍摄图片,请参阅 CameraX 的文档。
使用眼镜的摄像头拍摄视频流
如需捕获视频流而非图片,请将捕获图片示例中的 ImageCapture 组件替换为 VideoCapture 或 ImageAnalysis 组件,并更改捕获逻辑。
如需详细了解这些 API 及其使用方法,请参阅 CameraX 视频拍摄和 CameraX 图片分析文档。
选择分辨率和帧速率
您应查询设备,了解其支持的分辨率和相应的最大帧速率。下表列出了您可能会看到的值的示例,具体取决于应用的用例。为节省电池电量并减少眼镜发热,请选择适合您应用场景的最低分辨率和帧速率。
| 使用场景 | 分辨率 | 帧速率 |
|---|---|---|
| 文本识别 (OCR) 或世界感知 | 1920 x 1080 | 1 FPS |
| AI 视频流式传输(多模态助理) | 1024 x 768 | 1 FPS |
| 本地化和视觉定位 (VPS) | 640 x 360 或 640 x 480 | 10 FPS |
| 视频通话 | 640 x 360 或 640 x 480 | 24 FPS |
查询每个分辨率的最大帧速率
CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES 会报告设备的总体帧速率边界,该边界可能高于给定分辨率支持的流式传输速率。如需获取音频和显示眼镜上每个分辨率的实际最大值,请读取其最小帧时长,并使用 StreamConfigurationMap.getOutputMinFrameDuration(format, size) 将其转换为 FPS:
@androidx.annotation.OptIn(ExperimentalCamera2Interop::class) fun getMaxFpsBySize(cameraInfo: CameraInfo, format: Int): Map<Size, Int> { val map = Camera2CameraInfo.from(cameraInfo).getCameraCharacteristic( CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP ) ?: return emptyMap() return map.getOutputSizes(format).associateWith { size -> val minFrameDurationNs = map.getOutputMinFrameDuration(format, size) if (minFrameDurationNs > 0) (1_000_000_000L / minFrameDurationNs).toInt() else 0 } }
接下来,使用该值计算目标帧速率范围的 minFps 和 maxFps 边界。将下限 (minFps) 限制为根据 getOutputMinFrameDuration 计算出的分辨率最大串流帧速率,并设置更高的上限 (maxFps) 作为追赶窗口:
val maxFpsBySize = getMaxFpsBySize(cameraInfo, ImageFormat.YUV_420_888) val maxSupportedFps = maxFpsBySize[size] ?: return ImageAnalysis.Builder().build() // minFps is the target streaming frame rate and should be at most maxSupportedFps. val minFps = minOf(desiredFps, maxSupportedFps) // Set the upper bound to 2x minFps so the stream can catch up if frames are delayed. val maxFps = minFps * 2
代码要点
- 请使用与您的应用场景相符的格式。对于
ImageAnalysis,即YUV_420_888。 - 对于
VideoCapture,请改用Class重载:getOutputSizes(MediaRecorder::class.java)和getOutputMinFrameDuration(MediaRecorder::class.java, size)。 - 请指定一个
maxFps大于minFps的范围(例如minFps*2),而不是将两个边界都设置为相同的值(例如Range(minFps, minFps))。下限 (minFps) 用于设置目标串流帧速率,且不应超过根据getOutputMinFrameDuration计算出的值;上限 (maxFps) 则作为延迟帧的追赶窗口,以防止持续延迟。例如,对于 1 FPS 的视频流,该值为 [1,2] 或 [1,3];对于 24 FPS 的视频流,该值为 [24,30] 或 [24,48]。
配置帧速率
如需根据 CameraX 用例配置帧速率范围,请执行以下操作:
// Create and return the ImageAnalysis builder with proper frame rate ranges // ImageAnalysis: OCR, AI streaming, and VPS val analysisBuilder = ImageAnalysis.Builder() .setResolutionSelector(resolutionSelector) Camera2Interop.Extender(analysisBuilder) .setCaptureRequestOption( CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, Range(minFps, maxFps) ) return analysisBuilder.build()
此示例展示了 VideoCapture 和 ImageAnalysis 的配置,但您可以实现应用支持的任何用例。
了解数据流的行为
使用捕获流时,请注意以下系统行为:
- 不支持的分辨率会被拒绝:如果您请求的尺寸不在列表中,Camera2 会在数据流打开之前拒绝该配置。
- 请求的帧速率高于上限:如果您请求的最低帧速率高于分辨率支持的上限,会话仍会打开,但眼镜的目标帧速率会被限制在该支持的上限,而上限会继续作为追赶速率限制。例如,在 640 x 480 分辨率下请求 [30,60] 会将目标帧速率限制为 24 FPS(行为类似于 [24,60])。
- 热节流:当眼镜温度升高时,帧速率会下降,但分辨率保持不变。构建应用以处理较低或不均匀的帧速率,例如通过检查帧时间戳而不是假设固定速率。
从投影的 activity 访问手机的硬件
投射的 activity 还可以使用 createHostDeviceContext(context) 获取宿主设备(手机)的上下文,从而访问手机的硬件(例如摄像头或麦克风):
@OptIn(ExperimentalProjectedApi::class) fun getHostDeviceContext(context: Context): Context { // Obtain the host device (phone) context. // The `context` argument passed in can be any context (projected, host, Service, or App). return ProjectedContext.createHostDeviceContext(context) }
在混合应用(同时包含移动设备和眼镜体验的应用)中访问主机设备(手机)特有的硬件或资源时,您必须明确选择正确的上下文,以确保应用可以访问正确的硬件:
- 使用手机
Activity中的Activity上下文或ProjectedContext.createHostDeviceContext获取手机的上下文。 - 请勿使用
getApplicationContext,因为如果投射的 activity 是最近启动的组件,应用上下文可能会错误地返回眼镜的上下文。