如何在第三方Android应用中从Google Home获取Matter启用设备列表
第三方Android应用获取Google Home中Matter启用设备列表的实现方案
一、前提准备
- 完成Google Home开发者账号注册,创建项目并启用Home Graph API与Device Access API
- 为TestApp配置OAuth 2.0授权,确保应用具备访问用户智能家居设备数据的权限
- 确认用户已在Google Home中完成Nest Hub配对及MatterTestDevice的调配流程
二、核心实现步骤
1. 集成依赖库
在TestApp的build.gradle文件中添加相关依赖:
dependencies { implementation 'com.google.android.gms:play-services-auth:20.7.0' implementation 'com.google.apis:google-api-services-homegraph:v1-rev20240305-2.0.0' }
2. 用户授权流程
通过Google OAuth 2.0引导用户授权TestApp访问其Home设备数据,需请求https://www.googleapis.com/auth/homegraph权限:
val googleSignInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestScopes(Scope("https://www.googleapis.com/auth/homegraph")) .requestEmail() .build() val googleSignInClient = GoogleSignIn.getClient(this, googleSignInOptions) // 启动授权页面 startActivityForResult(googleSignInClient.signInIntent, RC_SIGN_IN)
在onActivityResult中获取授权凭证:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == RC_SIGN_IN) { val task = GoogleSignIn.getSignedInAccountFromIntent(data) try { val account = task.getResult(ApiException::class.java) val idToken = account.idToken // 调用接口获取设备列表 fetchDevices(idToken) } catch (e: ApiException) { // 处理授权失败逻辑 } } }
3. 调用Home Graph API筛选Matter设备
通过devices.query接口获取全量设备,再筛选出Matter启用的设备:
private fun fetchDevices(idToken: String) { val homegraph = Homegraph.Builder( AndroidHttp.newCompatibleTransport(), GsonFactory.getDefaultInstance(), GoogleAccountCredential.usingOAuth2(this, listOf("https://www.googleapis.com/auth/homegraph")) .setSelectedAccount(GoogleSignIn.getLastSignedInAccount(this)) ).setApplicationName("TestApp").build() val request = homegraph.devices().query(QueryRequest().apply { agentUserId = GoogleSignIn.getLastSignedInAccount(this@TestActivity)?.id }) Thread { try { val response = request.execute() val devices = response.payload?.devices // 筛选Matter设备 val matterDevices = devices?.filter { device -> device.traits?.contains("action.devices.traits.Matter") == true } // 定位并处理MatterTestDevice的信息 matterDevices?.forEach { device -> if (device.name?.name == "MatterTestDevice") { val deviceInfo = """ 设备名称:${device.name?.name} 设备ID:${device.id} 设备类型:${device.type} Matter相关属性:${device.traits?.joinToString(", ")} """.trimIndent() // 主线程更新UI展示信息 runOnUiThread { tv_device_info.text = deviceInfo } } } } catch (e: IOException) { // 处理API调用异常 } }.start() }
三、关键注意事项
- 需保证目标Matter设备已完成Google Home中的调配流程且处于在线状态
- 授权流程必须请求正确的权限范围,否则无法访问Home Graph数据
- API调用需在子线程执行,避免阻塞主线程
- 需处理网络错误、权限过期等异常场景
内容的提问来源于stack exchange,提问作者TechDubey
相关产品推荐
相关产品推荐

