Hub Activation API trên Android

HubManagementTrait

Khi sử dụng API Kích hoạt thiết bị trung tâm, bạn có thể tạo một ứng dụng có thể khám phá và kích hoạt các thiết bị 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 hoạt động như thiết bị 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 một thiết bị có khả năng hoạt động như thiết bị trung tâm:

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