使用投影內容存取智慧音訊眼鏡和智慧螢幕眼鏡的硬體

適用的 XR 裝置
本指南可協助您為這類 XR 裝置打造體驗。
音訊和
顯示型眼鏡

要求並取得必要權限後,應用程式就能存取語音眼鏡或顯示型眼鏡的硬體。如要存取眼鏡的硬體 (而非手機的硬體),關鍵在於使用投影情境。

取得投影內容的主要方式有兩種,取決於程式碼的執行位置:

如果程式碼在投影活動中執行,則取得投影內容

如果應用程式的程式碼是從投影活動中執行,其活動內容本身就是投影內容。在這種情況下,該活動中的呼叫已可存取眼鏡的硬體。

取得在「電話」應用程式元件中執行的程式碼投影內容

如果應用程式中投影活動以外的部分 (例如手機活動或服務) 需要存取眼鏡的硬體,就必須明確取得投影情境。方法是使用 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
        }
    }
}

檢查有效性

使用 ProjectedContext.isProjectedDeviceConnected 包裝 createProjectedDeviceContext 呼叫。雖然這個方法會傳回 true,但投影情境對連結裝置仍有效,且「電話」應用程式活動或服務 (例如 CameraManager) 可以存取眼鏡硬體。

中斷連線時清除

投影情境會繫結至連結裝置的生命週期,因此會在裝置中斷連線時刪除。裝置中斷連線時,ProjectedContext.isProjectedDeviceConnected 會傳回 false。應用程式應監聽這項變更,並清除應用程式使用該投影內容建立的任何系統服務 (例如 CameraManager) 或資源。

重新連線時重新初始化

眼鏡重新連線後,應用程式可以使用 createProjectedDeviceContext 取得另一個投影情境例項,然後使用新的投影情境重新初始化任何系統服務或資源。

使用眼鏡的麥克風錄音

你可以使用藍牙免持設定檔 (HFP),透過眼鏡錄製音訊。 在這個模式下,眼鏡會使用標準耳機和進階音訊傳輸設定檔 (A2DP) 設定檔連線至手機,運作方式與一般藍牙周邊裝置類似。如果應用程式已設計為標準藍牙錄音,您可以使用這個方法錄製眼鏡的音訊,不需額外開發。

使用藍牙 HFP 錄音

如要使用藍牙 HFP 錄製音訊,請先要求必要的執行階段權限,然後使用 AudioManager API 錄製音訊,如以下各節所述。

要求權限

與任何標準藍牙音訊裝置一樣,RECORD_AUDIO、BLUETOOTH_CONNECT 和其他相關權限是由手機控制,而非連結裝置 (例如語音眼鏡或顯示型眼鏡)。

請按照下列步驟要求權限:

  1. 在應用程式的資訊清單檔案中宣告下列權限:

  2. 使用標準 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,而不是在眼鏡連線時立即開啟相機。眼鏡和主機之間的非同步設定必須在 OS 完成重新建立眼鏡相機之前完成,而且眼鏡相機也可能在連線時動態消失 (例如在熱緩解期間)。
    • 新增攝影機 (onCamerasAdded):在 availableCameraInfos 更新並加入新攝影機後觸發,避免在設定期間發生時間競爭。
    • 移除相機 (onCamerasRemoved):追蹤相機是否存在,而非使用狀態,因此解除繫結時,只有在移除眼鏡相機時才會釋出資源,而不是在應用程式開啟相機時做出反應。
  • 中斷連線時清除:當眼鏡中斷連線或活動刪除時,傳回 monitorProjectedDeviceConnectivity 的清除閉包會呼叫 removeCameraPresenceListener 和 unbindAll()。
  • 動態選取攝影機:使用 isOf,將傳遞至 onCamerasAdded 的 CameraIdentifier 與 availableCameraInfos 進行比對,動態選取眼鏡的攝影機。
  • 自訂解析度:建構 ResolutionSelector,指定範例 16:9 顯示比例和偏好的 ImageCapture 解析度 (會改用最接近的較低支援大小)。支援的顯示比例和解析度因眼鏡裝置和模式而異 (例如 4:3 和 16:9),因此如需查看確切支援的大小,請查詢 StreamConfigurationMap。
  • 生命週期繫結:將 ImageCapture 繫結至 LifecycleOwner,根據活動的生命週期,自動管理相機開啟和關閉轉換。
  • 設定單一串流硬體:眼鏡的相機管道一次只能有一個有效的串流。單獨繫結 ImageCapture 時,CameraX 預設會附加內部重複串流 (MeteringRepeating) 進行對焦和測光,導致單一串流管道停滯。在傳遞至 LifecycleCameraProvider.createInstance 的 CameraXConfig 中傳遞 setRepeatingStreamForced(false),這樣 ImageCapture 就能在沒有預覽串流的情況下繫結。

設定好眼鏡的相機後,您可以使用 CameraX 的 ImageCapture 類別擷取圖片。請參閱 CameraX 說明文件,瞭解如何使用 takePicture 擷取圖片。

使用眼鏡的攝影機擷取串流

如要擷取串流而非圖片,請將擷取圖片範例中的 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

程式碼重點

設定影格率

如要根據 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 會在串流開啟前拒絕設定。
  • 要求高於上限的影格率:如果您要求的最低影格率高於解析度支援的上限,工作階段仍會開啟,但眼鏡的目標影格率會限制在支援的上限,而上限會繼續做為趕上速率限制。舉例來說,如果要求 [30,60] 且解析度為 640 x 480,目標影格率會限制為 24 FPS (行為類似 [24,60])。
  • 熱調節:眼鏡溫度上升時,影格率會下降,但解析度維持不變。建構應用程式來處理較低或不均勻的影格率,例如檢查影格時間戳記,而非假設固定速率。

透過投影活動存取手機硬體

投影活動也可以使用 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)
}

在混合式應用程式 (同時包含手機和眼鏡體驗的應用程式) 中,存取主機裝置 (手機) 專屬的硬體或資源時,必須明確選取正確的結構定義,確保應用程式能存取正確的硬體: