Hub Activation API trên Android

Hub Activation API cho phép bạn khám phá và kích hoạt một trung tâm Google Home theo phương pháp lập trình. Tính năng này đặc biệt hữu ích khi người dùng không có cách nào khác để kích hoạt trung tâm, chẳng hạn như trong trường hợp trung tâm không có màn hình.

Bằng cách sử dụng Hub Activation API, bạn có thể tạo một ứng dụng có thể khám phá và kích hoạt các trung tâm. Để thực hiện việc này:

  1. Tạo một tham chiếu đến HubManagementTrait trong cấu trúc:

    val hubManagementTrait =
      hubManagementTraitFlow.firstOrNull {
        it.metadata.sourceConnectivity?.connectivityState == ConnectivityState.ONLINE
      }
    if (hubManagementTrait == null) {
      errorsEmitter.emit(HomeException.notFound("HubManagement trait isn't online"))
    }
    
  2. Xác định mọi thiết bị có khả năng làm trung tâm trên mạng 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. Kích hoạt thiết bị có thể làm thiết bị trung tâm:

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