Flutter通知管理插件notifications的使用

Flutter通知管理插件notifications的使用

介绍

notifications 是一个用于监控Android设备上的通知的Flutter插件。它允许开发者监听并处理设备上收到的通知事件。

安装

pubspec.yaml 中添加依赖

确保在你的 pubspec.yaml 文件中添加了 notifications 作为依赖项。你可以参考官方文档来了解如何正确添加依赖。

dependencies:
  notifications: ^最新版本号

修改 AndroidManifest.xml

在你的 AndroidManifest.xml 文件中的 <application> 标签内添加以下代码片段,以注册必要的服务:

<service
    android:label="notifications"
    android:name="dk.cachet.notifications.NotificationListener"
    android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
    <intent-filter>
        <action android:name="android.service.notification.NotificationListenerService" />
    </intent-filter>
</service>

使用方法

监听通知

为了监听来自其他应用的通知,你需要创建一个 StreamSubscription<NotificationEvent> 来订阅 notificationStream 流。下面是一个简单的例子,展示了如何设置和取消监听器。

示例代码

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:notifications/notifications.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Notifications? _notifications;
  StreamSubscription<NotificationEvent>? _subscription;
  List<NotificationEvent> _log = [];
  bool started = false;

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // 初始化平台状态
  Future<void> initPlatformState() async {
    startListening();
  }

  // 处理接收到的通知数据
  void onData(NotificationEvent event) {
    setState(() {
      _log.add(event);
    });
    print(event.toString());
  }

  // 开始监听通知
  void startListening() {
    _notifications = Notifications();
    try {
      _subscription = _notifications!.notificationStream!.listen(onData);
      setState(() => started = true);
    } on NotificationException catch (exception) {
      print(exception);
    }
  }

  // 停止监听通知
  void stopListening() {
    _subscription?.cancel();
    setState(() => started = false);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Notifications Example app'),
        ),
        body: Center(
            child: ListView.builder(
                itemCount: _log.length,
                reverse: true,
                itemBuilder: (BuildContext context, int idx) {
                  final entry = _log[idx];
                  return ListTile(
                      leading: Text(entry.timeStamp.toString().substring(0, 19)),
                      trailing: Text(entry.packageName.toString().split('.').last));
                })),
        floatingActionButton: FloatingActionButton(
          onPressed: started ? stopListening : startListening,
          tooltip: 'Start/Stop sensing',
          child: Icon(started ? Icons.stop : Icons.play_arrow),
        ),
      ),
    );
  }
}

此示例应用程序会启动一个监听器来捕获所有传入的通知,并将它们显示在一个列表视图中。每个条目包含通知的时间戳和发出该通知的应用程序包名。

NotificationEvent 属性

每当有新的通知到来时,NotificationEvent 对象会被传递给监听函数。这个对象包含了关于通知的信息,如标题、消息内容、包名以及时间戳等。

  • title: 通知的标题
  • message: 通知的消息内容
  • packageName: 发出通知的应用程序包名
  • timeStamp: 通知发生的时间戳

通过这些属性,你可以根据需要自定义UI或逻辑处理。

以上就是关于 notifications 插件的基本用法介绍,希望对大家有所帮助!如果你有任何问题或者建议,请随时留言交流。


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

1 回复

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


在Flutter中,管理通知通常涉及使用第三方插件来集成设备的通知系统。flutter_local_notifications 是一个流行的插件,允许你在Flutter应用中创建、调度和展示本地通知。下面是一个简单的代码示例,展示了如何使用 flutter_local_notifications 插件来管理通知。

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

dependencies:
  flutter:
    sdk: flutter
  flutter_local_notifications: ^9.0.0  # 请检查最新版本号

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

接下来,在你的 Dart 代码中,你需要进行以下步骤:

  1. 初始化插件:在应用启动时初始化通知插件。
  2. 配置通知:设置通知的图标、通道等。
  3. 发送通知:创建并发送通知。

以下是一个完整的示例代码:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Notifications Example'),
        ),
        body: Center(
          child: NotificationButton(),
        ),
      ),
    );
  }
}

class NotificationButton extends StatefulWidget {
  @override
  _NotificationButtonState createState() => _NotificationButtonState();
}

class _NotificationButtonState extends State<NotificationButton> {
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  var initializationSettings;

  @override
  void initState() {
    super.initState();
    var androidChannel = AndroidNotificationChannel(
      'high_importance_channel', // id
      'High Importance Notifications', // title
      'This channel is used for important notifications.', // description
      importance: Importance.High,
    );
    var iOSChannel = IOSNotificationChannel(
      'high_importance_channel', // id
      'High Importance Notifications', // title
      'This channel is used for important notifications.' // description
    );
    initializationSettings = InitializationSettings(
      android: AndroidInitializationSettings(channels: [androidChannel]),
      iOS: IOSInitializationSettings(channels: [iOSChannel])
    );

    flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: (String? payload) async {
      if (payload != null) {
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text('Payload'),
              content: Text(payload!),
              actions: <Widget>[
                TextButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: Text('OK'),
                ),
              ],
            );
          },
        );
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () async {
        var notificationDetails = NotificationDetails(
          android: AndroidNotificationDetails(
            'high_importance_channel',
            'High Importance Channel',
            importance: Importance.High,
            priority: Priority.High
          ),
          iOS: IOSNotificationDetails(
            presentAlert: true,
            presentSound: true,
            presentBadge: true,
          ),
        );

        await flutterLocalNotificationsPlugin.show(
          0, // id
          'Hello, World!', // title
          'This is a local notification', // body
          notificationDetails,
          payload: 'item x',
        );
      },
      child: Text('Show Notification'),
    );
  }
}

在这个示例中:

  • 我们首先初始化了 FlutterLocalNotificationsPlugin 并设置了 Android 和 iOS 的通知通道。
  • NotificationButtononPressed 回调中,我们创建并显示了一个本地通知。
  • 用户点击通知时,会显示一个包含通知负载(payload)的对话框。

确保你已经按照插件的文档配置了 Android 和 iOS 项目中的必要权限和设置。例如,在 Android 中,你可能需要在 AndroidManifest.xml 中添加通知权限,并在 res/xml 文件夹中定义通知通道。在 iOS 中,你需要在 Info.plist 中添加必要的权限声明。

这个示例展示了如何使用 flutter_local_notifications 插件进行基本的通知管理。你可以根据需求进一步扩展这个示例,比如处理不同类型的通知、调度定时通知等。

回到顶部