在使用任何 Android 版 Google Home API 之前,您必須先在應用程式中初始化 Google Home。在這一步中,您將為本機內容建立 Home
的 單例例項。
一次只能啟用一個 Home
例項。
這是 Home API 的進入點,也涉及宣告您打算與 Device & Structure 和 Automation API 搭配使用的特徵和裝置類型。如果你剛開始使用 Google Home 生態系統,不確定要註冊哪些特徵或裝置類型,我們在這份指南中提供一些最常見的選項。
建立 Home 例項
首先,請將下列套件匯入應用程式:
import android.content.Context
import com.google.home.FactoryRegistry
import com.google.home.HomeConfig
import com.google.home.Home
如要初始化 Home API,請按照下列步驟操作:
取得
Application
結構定義的參照。這個內容不會依附於任何活動生命週期,只要應用程式處於運作狀態,就會持續運作。您可以呼叫Context.getApplicationContext()
或Activity.getApplication()
來取得。val context = Context.getApplicationContext()
建立
FactoryRegistry
例項,並加入您打算在應用程式中使用的所有特徵和裝置類型。在本指南中,我們會建議一些常見的裝置類型 (燈具、插頭、感應器、開關和溫度控制器)、自動化動作的狀態和 Google 助理特徵,以防你不確定自己需要哪些裝置。詳情請參閱「特徵和裝置類型的註冊」。
val registry = FactoryRegistry( traits = listOf( AirQuality, AreaAttendanceState, AreaPresenceState, AssistantBroadcast, AssistantFulfillment, BooleanState, ColorControl, ExtendedColorControl, FlowMeasurement, IlluminanceMeasurement, LevelControl, Notification, OccupancySensing, OnOff, RelativeHumidityMeasurement, Switch, TemperatureMeasurement, Thermostat), types = listOf( AirQualitySensorDevice, ColorDimmerSwitchDevice, ColorTemperatureLightDevice, ContactSensorDevice, DimmableLightDevice, DimmablePlugInUnitDevice, DimmerSwitchDevice, ExtendedColorLightDevice, FlowSensorDevice, GenericSwitchDevice, HumiditySensorDevice, LightSensorDevice, OccupancySensorDevice, OnOffLightDevice, OnOffLightSwitchDevice, OnOffPluginUnitDevice, OnOffSensorDevice, SpeakerDevice, TemperatureSensorDevice, ThermostatDevice))
您必須為此處註冊的每個特徵和裝置類型提供匯入陳述式 (Android Studio 應會提示您新增這些項目)。
使用
Dispatchers.IO
協同程式背景資訊和註冊例項,將HomeConfig
例項化。val homeConfig = HomeConfig( coroutineContext = Dispatchers.IO, factoryRegistry = registry)
最後,請使用
HomeConfig
和結構定義建立Home
的 單例例項,這是 API 的進入點。val homeManager: HomeClient = Home.getClient(context, homeConfig)
為了避免出現無效工作階段的錯誤,請務必只建立 Home
的單例例項,並將其包裝在物件宣告中。
舉例來說,範例應用程式會以以下方式執行這項操作:
internal object HomeClientModule {
@Provides
@Singleton
fun provideHomeClient(@ApplicationContext context: Context): HomeClient {
return Home.getClient(
context,
HomeConfig(
coroutineContext = IODispatcherModule.provideIoDispatcher(),
factoryRegistry = registry,
),
)
}
}
註冊特徵和裝置類型
FactoryRegistry
類別可協助開發人員明確指出應用程式使用的特徵和裝置類型,進而縮減應用程式二進位檔案的大小。
請注意,權限和工廠註冊已解除連結。因此,如果應用程式可使用權限,但未在工廠註冊表中註冊的未註冊特徵和類型,就無法透過 Automation API 存取,也不會在大量 traits()
或 types()
方法呼叫中傳回。