API Hub Activation su Android

L'API Hub Activation consente di rilevare e attivare in modo programmatico un hub Google Home. È particolarmente utile quando l'utente non ha altro modo per attivare un hub, come nel caso di un hub senza schermo.

Utilizzare l'API Hub Activation

Utilizzando l'API Hub Activation, puoi creare un'app in grado di rilevare e attivare gli hub.

  1. Ottieni un riferimento a HubManagementTrait nella struttura:

    val hubManagementTrait =
      hubManagementTraitFlow.firstOrNull {
        it.metadata.sourceConnectivity?.connectivityState == ConnectivityState.ONLINE
      }
    if (hubManagementTrait == null) {
      errorsEmitter.emit(HomeException.notFound("HubManagement trait isn't online"))
    }
    
  2. Identifica eventuali dispositivi compatibili con il hub sulla rete 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. Attiva un dispositivo compatibile con l'hub:

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