Android 上的 Hub Activation API

您可以使用 Hub Activation API,以程式輔助方式探索及啟用 Google Home Hub。如果使用者無法透過其他方式啟動中樞裝置 (例如沒有螢幕的中樞裝置),這項功能就特別實用。

使用 Hub Activation API

您可以使用 Hub Activation API 建構應用程式,以便探索及啟用中樞裝置。

  1. 取得結構中的 HubManagementTrait 參照:

    val hubManagementTrait =
      hubManagementTraitFlow.firstOrNull {
        it.metadata.sourceConnectivity?.connectivityState == ConnectivityState.ONLINE
      }
    if (hubManagementTrait == null) {
      errorsEmitter.emit(HomeException.notFound("HubManagement trait isn't online"))
    }
    
  2. 找出 Wi-Fi 網路上任何可做為中樞裝置的裝置:

    try {
      val unused = hubManagementTrait.discoverAvailableHubs()
    } catch (e: Exception) {
      Log.d(TAG_HUB_DISCOVERY, "Error discovering hubs $e")
      errorsEmitter.emit(e)
    }
    
    val hubManagementTraitFlow = structureFlow.flatMapLatest { it.trait(HubManagement) }
    
    val discoveredHubs =
      hubManagementTraitFlow
        .map { it.discoveredHubsList }
        .handleErrors()
        .flowOn(ioDispatcher)
        .stateIn(
          scope = CoroutineScope(viewModelScope.coroutineContext + ioDispatcher),
          started = SharingStarted.WhileSubscribed(),
          listOf(),
        )
    
  3. 啟用支援中樞裝置的裝置:

    try {
      val unused = hubManagementTrait.activateHub(hub)
    } catch (e: Exception) {
      Log.d("Hub Activation", "Error activating hub $e")
    }