在运行时检查音频眼镜和显示眼镜的设备可用性

适用的 XR 设备
本指南可帮助您为以下类型的 XR 设备打造优质体验。
音频和
显示眼镜

用户在日常生活中使用音频眼镜或显示眼镜时,眼镜可能会与主机设备(例如用户的手机)断开连接,或者用户摘下眼镜时,眼镜可能会暂时无法使用。为了应对设备可用性方面的这些变化,您的应用可以使用 XR 设备可用性 API,该 API 会将设备可用性信号整合到标准 Android Lifecycle.State 值中。使用此 API 可帮助管理音频路由、启动指令激活,并根据眼镜的可用时间了解何时需要用户输入。

了解生命周期状态

下表列出了设备可用性信号与 Lifecycle.State 值的对应关系。

生命周期状态

设备状态

说明

INITIALIZED

创建日期

生命周期对象已创建,但尚未被观测。

CREATED

无效

服务已连接,但用户未佩戴设备。

STARTED

有效

用户佩戴着设备。

DESTROYED

已断开连接

设备已断开连接或服务连接已断开。

检查和监控设备可用性

如需检查和监控设备的可用性,您将使用投影的上下文以及生命周期状态来确定应用应如何处理每种情况:

    // In your phone activity or service, check for projected device connection state before
    // attempting to create a projected device context and get the device lifecycle.
    ProjectedContext.isProjectedDeviceConnected(context, currentCoroutineContext())
        .flatMapLatest { isConnected ->
            if (isConnected) {
                try {
                    // Create the projected device context on connection
                    val projectedContext = ProjectedContext.createProjectedDeviceContext(context)
                    val xrDevice = XrDevice.getCurrentDevice(projectedContext)

                    // Get the device lifecycle
                    xrDevice.getLifecycle().currentStateFlow
                } catch (e: IllegalStateException) {
                    flowOf(Lifecycle.State.DESTROYED)
                }
            } else {
                flowOf(Lifecycle.State.DESTROYED)
            }
        }
        .collect { state ->
            when (state) {
                Lifecycle.State.STARTED -> { /* Device is available (worn) */ }
                Lifecycle.State.CREATED -> { /* Device is unavailable (not worn) */ }
                Lifecycle.State.DESTROYED -> { /* Device is disconnected from host phone */ }
                else -> { /* Handle other states */ }
            }
        }
}

代码要点

  • 检查连接:在访问设备生命周期之前,请调用 ProjectedContext.isProjectedDeviceConnected 以验证投影设备是否已连接到宿主设备。
  • 获取 ProjectedContext:仅在验证连接后调用 ProjectedContext.createProjectedDeviceContext,并确保将此上下文传递到 XrDevice 实例中。
  • 处理上下文失效问题:每次投影设备连接时,都会生成新的 deviceId。一旦状态达到 DESTROYED,当前的 ProjectedContext 便无效。立即停止使用,并等待新的连接。
  • 优化电池和资源:根据生命周期状态妥善处理应用功能,以节省系统资源并减少电池消耗。例如,当状态从 STARTED 转换回 CREATED 时,您应释放眼镜专用资源,例如相机数据流。CREATED 状态表示设备不再被佩戴,因此停止这些进程对于防止不必要的耗电和提升用户隐私至关重要。