如何在Flutter应用中通过按钮触发Google Assistant控制SONOFF车库门
实现Flutter按钮触发Google Assistant控制车库门
以下是几种可行的实现方案,可根据你的需求选择:
方案一:Android平台通过Intent唤起Google Assistant
针对Android设备,可以通过Flutter的MethodChannel调用原生Android代码,唤起Google Assistant并传入指令文本:
Flutter端代码
import 'package:flutter/services.dart'; // 点击按钮时调用此方法 void triggerGarageDoorCommand() async { const platform = MethodChannel('com.your.app/garage_door'); try { await platform.invokeMethod('sendCommand', {'command': '激活车库门'}); } on PlatformException catch (e) { print("触发失败: ${e.message}"); } }
Android原生端代码(MainActivity)
import io.flutter.embedding.android.FlutterActivity; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.plugin.common.MethodChannel; import android.content.Intent; import android.speech.RecognizerIntent; public class MainActivity extends FlutterActivity { private static final String CHANNEL = "com.your.app/garage_door"; @Override public void configureFlutterEngine(FlutterEngine flutterEngine) { super.configureFlutterEngine(flutterEngine); new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL) .setMethodCallHandler( (call, result) -> { if (call.method.equals("sendCommand")) { String command = call.argument("command"); // 唤起Google Assistant并传入指令 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH); intent.putExtra(RecognizerIntent.EXTRA_QUERY, command); startActivity(intent); result.success(null); } else { result.notImplemented(); } } ); } }
方案二:使用Google Assistant SDK(官方深度集成)
如果需要更直接的集成,可以使用Google Assistant SDK,不过配置流程较复杂:
- 在Google Cloud Console创建项目,启用Google Assistant SDK并获取OAuth2凭据
- 在Flutter项目中集成相关依赖包,实现认证与指令发送:
import 'package:google_assistant_sdk/google_assistant_sdk.dart'; void sendCommand() async { final assistant = GoogleAssistant(); // 处理OAuth2认证流程 await assistant.authenticate(); // 发送指令 final response = await assistant.sendTextQuery('激活车库门'); print(response); }
方案三:通过Webhook间接触发(跨平台友好)
借助IFTTT或Google Home自动化创建Webhook,Flutter通过HTTP请求调用Webhook来触发车库门操作:
import 'package:http/http.dart' as http; void triggerGarageDoor() async { final webhookUrl = Uri.parse('你的Webhook地址'); final response = await http.post(webhookUrl); if (response.statusCode == 200) { print('指令已发送'); } else { print('发送失败'); } }
内容的提问来源于stack exchange,提问作者Alexandros Tziokas
相关产品推荐
相关产品推荐

