Flutter物联网通知插件iot_notification的使用

Flutter物联网通知插件iot_notification的使用

简介

iot_notification 是一个用于实现物联网通知功能的 Flutter 插件。该插件支持多种功能,包括设备管理、MQTT 客户端连接、电池优化设置、日志记录等。


使用步骤

1. 添加依赖

pubspec.yaml 文件中添加以下依赖项:

dependencies:
  iot_notification: ^版本号

然后运行以下命令以更新依赖:

flutter pub get

2. 初始化插件

首先,确保在 main.dart 中导入必要的包并初始化插件。

import 'package:flutter/material.dart';
import 'package:iot_notification/iot_notification.dart';

3. 示例代码

以下是完整的代码示例,展示了如何使用 iot_notification 插件实现物联网通知功能。

主程序代码

import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
import 'package:iot_notification/iot_notification.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // 创建事件通道监听
  static const EventChannel _events = EventChannel('iot_notification_events');

  [@override](/user/override)
  void initState() {
    super.initState();

    // 监听来自 IoT 服务的事件流
    _events.receiveBroadcastStream().listen((Object? event) async {
      if (event != null) {
        print("收到事件: $event");
      }
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Iot Notification 示例'),
        ),
        body: SingleChildScrollView(
          child: Center(
            child: Column(
              children: [
                // 启动服务
                ElevatedButton(
                  child: Text("启动服务"),
                  onPressed: () async {
                    IotNotification.startService(
                      userAccessToken: "用户访问令牌",
                      userRefreshToken: "用户刷新令牌",
                      devAccessToken: "开发人员访问令牌",
                      devRefreshToken: "开发人员刷新令牌",
                      mqttClientIdentifier: "客户端标识符",
                      brokerAddress: "broker地址",
                      brokerProtocol: "协议类型(如 ssl)",
                      brokerPort: 8883,
                      authServer: "认证服务器地址",
                      apiServer: "API 服务器地址",
                      rootCA: '',
                    );
                  },
                ),

                // 添加设备
                ElevatedButton(
                  child: Text("添加设备"),
                  onPressed: () async {
                    IotNotification.addDevice(jsonEncode({
                      "id": "设备ID",
                      "sn": "设备序列号",
                      "name": "设备名称",
                      "state": "设备状态",
                      "desc": "设备描述",
                      "developer_id": "开发者ID",
                      "options": null,
                    }));
                  },
                ),

                // 扫描二维码
                ElevatedButton(
                  child: Text("扫描二维码"),
                  onPressed: () async {
                    String? result = await IotNotification.scan();
                    print("扫描结果: $result");
                  },
                ),

                // 获取设备密钥
                ElevatedButton(
                  child: Text("获取设备密钥"),
                  onPressed: () async {
                    List<String> keys = await IotNotification.getKeys();
                    print("密钥1: ${keys[0]}");
                    print("密钥2: ${keys[1]}");
                  },
                ),

                // 停止服务
                ElevatedButton(
                  child: Text("停止服务"),
                  onPressed: () async {
                    IotNotification.stopService();
                  },
                ),

                // 取消警报
                ElevatedButton(
                  child: Text("取消警报"),
                  onPressed: () async {
                    IotNotification.cancelAlarm();
                  },
                ),

                // 请求警报权限
                ElevatedButton(
                  child: Text("请求警报权限"),
                  onPressed: () async {
                    IotNotification.requestAlarmPermission();
                  },
                ),

                // 忽略电池优化
                ElevatedButton(
                  child: Text("忽略电池优化"),
                  onPressed: () async {
                    IotNotification.ignoreBatteryOptimization();
                  },
                ),

                // 打开电池设置页面
                ElevatedButton(
                  child: Text("打开电池设置"),
                  onPressed: () async {
                    IotNotification.openBatterySettings();
                  },
                ),

                // 请求发送通知权限
                ElevatedButton(
                  child: Text("请求发送通知权限"),
                  onPressed: () async {
                    IotNotification.requestPostNotificationsPermission();
                  },
                ),

                // 初始化日志
                ElevatedButton(
                  child: Text("初始化日志"),
                  onPressed: () async {
                    IotNotification.initLogger(
                      "环境类型",
                      "日志级别",
                      "用户名",
                      "密码",
                      "服务器地址",
                      "应用名",
                      "设备类型",
                    );
                  },
                ),

                // 打开文件管理器
                ElevatedButton(
                  child: Text("打开文件管理器"),
                  onPressed: () {
                    IotNotification.openFileManager();
                  },
                ),

                // 插入事件
                ElevatedButton(
                  child: Text("插入事件"),
                  onPressed: () {
                    IotNotification.insertEvent(
                      sender: "系统",
                      title: "随机标题",
                      description: "这是描述",
                    );
                  },
                ),

                // 获取所有事件
                ElevatedButton(
                  child: Text("获取所有事件"),
                  onPressed: () async {
                    List<Events> events = await IotNotification.getAllEvents();
                    events.forEach((element) {
                      print("事件ID: ${element.id}, 创建时间: ${element.createdAt}");
                    });
                  },
                ),

                // 清空事件
                ElevatedButton(
                  child: Text("清空事件"),
                  onPressed: () {
                    IotNotification.clearEvents();
                  },
                ),

                // 显示全屏意图
                ElevatedButton(
                  child: Text("显示全屏意图"),
                  onPressed: () {
                    IotNotification.showFullScreenIntent();
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

更多关于Flutter物联网通知插件iot_notification的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter物联网通知插件iot_notification的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


iot_notification 是一个用于在 Flutter 应用中处理物联网(IoT)通知的插件。它可以帮助你接收、显示和管理来自 IoT 设备的通知。以下是如何在 Flutter 项目中使用 iot_notification 插件的基本步骤。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 iot_notification 插件的依赖。

dependencies:
  flutter:
    sdk: flutter
  iot_notification: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来获取依赖。

2. 初始化插件

在你的 Flutter 应用中初始化 iot_notification 插件。通常是在 main.dart 文件中进行初始化。

import 'package:flutter/material.dart';
import 'package:iot_notification/iot_notification.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 iot_notification 插件
  await IotNotification.initialize();

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'IoT Notification Demo',
      home: HomeScreen(),
    );
  }
}

3. 接收通知

你可以使用 IotNotification 插件来接收来自 IoT 设备的通知。通常,你会使用一个 StreamBuilder 来监听通知流并更新 UI。

import 'package:flutter/material.dart';
import 'package:iot_notification/iot_notification.dart';

class HomeScreen extends StatefulWidget {
  [@override](/user/override)
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  [@override](/user/override)
  void initState() {
    super.initState();
    // 监听通知流
    IotNotification.onNotificationReceived.listen((notification) {
      // 处理接收到的通知
      print('Received notification: $notification');
      // 更新 UI 或显示通知
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('IoT Notification Demo'),
      ),
      body: Center(
        child: Text('Waiting for IoT notifications...'),
      ),
    );
  }
}

4. 发送通知(可选)

如果你需要从你的 Flutter 应用发送通知到 IoT 设备,你可以使用 IotNotification.sendNotification 方法。

void sendNotificationToDevice() async {
  String deviceId = 'your_device_id';
  String message = 'Hello from Flutter!';
  
  await IotNotification.sendNotification(deviceId, message);
}

5. 处理通知点击事件

你还可以处理用户点击通知的事件,以便在用户点击通知时执行特定操作。

IotNotification.onNotificationClicked.listen((notification) {
  // 处理通知点击事件
  print('Notification clicked: $notification');
  // 导航到特定页面或执行其他操作
});

6. 配置通知通道(Android)

在 Android 上,你可能需要配置通知通道以确保通知能够正确显示。

await IotNotification.configureNotificationChannel(
  channelId: 'iot_notifications',
  channelName: 'IoT Notifications',
  channelDescription: 'Notifications from IoT devices',
  importance: NotificationImportance.High,
);

7. 处理权限(iOS)

在 iOS 上,你可能需要请求通知权限。

await IotNotification.requestNotificationPermissions();

8. 处理后台通知(可选)

如果你需要处理后台通知,你可以使用 IotNotification.configureBackgroundHandler 方法。

IotNotification.configureBackgroundHandler((notification) async {
  // 处理后台通知
  print('Background notification: $notification');
});

9. 清理资源

在应用生命周期结束时,你可以选择清理资源。

[@override](/user/override)
void dispose() {
  IotNotification.dispose();
  super.dispose();
}
回到顶部