Flutter通知读取插件notification_reader的使用
Flutter通知读取插件notification_reader的使用
在您的Flutter应用中读取通知。
开始使用
在您的Flutter项目中添加插件
在pubspec.yaml文件中添加以下依赖:
dependencies:
  notification_reader: ^版本号
然后运行以下命令安装插件:
flutter pub get
在AndroidManifest.xml中添加服务
在android/app/src/main/AndroidManifest.xml文件中,在<application>标签内添加以下代码:
<service android:name="com.fluttterbuddy.notification_reader.NotificationService"
    android:label="NotificationService"
    android:exported="true"
    android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
    <intent-filter>
        <action android:name="android.service.notification.NotificationListenerService" />
    </intent-filter>
</service>
导入插件
在您的Dart文件中导入插件:
import 'package:notification_reader/notification_reader.dart';
打开通知读取设置
首先,您需要让用户手动打开通知读取设置:
await NotificationReader.openNotificationReaderSettings;
获取通知数据
您可以使用以下代码来获取通知数据:
NotificationData res = await NotificationReader.onNotificationRecieve();
NotificationData类
NotificationData类包含以下属性:
res.packageName; // 应用包名
res.title; // 通知标题
res.body; // 通知正文
res.data; // 以Json格式存储的数据
示例代码
以下是一个完整的示例代码,演示如何在Flutter应用中使用notification_reader插件:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:notification_reader/notification_reader.dart';
void main() {
  runApp(const MyApp());
}
class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);
  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
  List<NotificationData> titleList = [];
  [@override](/user/override)
  void initState() {
    super.initState();
    initPlatformState();
  }
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('通知读取器'),
        ),
        body: SingleChildScrollView(
          child: Column(
            children: [
              const SizedBox(
                height: 10,
              ),
              ElevatedButton(
                  onPressed: () async {
                    await NotificationReader.openNotificationReaderSettings;
                  },
                  child: Text("打开设置")),
              ElevatedButton(
                  onPressed: () async {
                    initPlatformState();
                  },
                  child: const Text("重新加载")),
              ListView.builder(
                shrinkWrap: true,
                primary: false,
                reverse: true,
                itemCount: titleList != null ? titleList.length : 0,
                itemBuilder: (c, i) {
                  return SizedBox(
                    height: 100,
                    child: Card(
                      elevation: 5,
                      margin: EdgeInsets.all(8),
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            const Spacer(),
                            Text(titleList[i].title ?? ""),
                            const Spacer(),
                            Text(titleList[i].body ?? ""),
                            const Spacer(),
                            Text(titleList[i].packageName ?? ""),
                            const Spacer(),
                          ],
                        ),
                      ),
                    ),
                  );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
  Future<void> initPlatformState() async {
    NotificationData res = await NotificationReader.onNotificationRecieve();
    if (res.body != null) {
      Timer.periodic(Duration(seconds: 1), (timer) async {
        var res = await NotificationReader.onNotificationRecieve();
        if (!titleList.contains(res)) {
          setState(() {
            titleList.add(res);
          });
        }
      });
    }
  }
}
更多关于Flutter通知读取插件notification_reader的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter通知读取插件notification_reader的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何在Flutter项目中使用notification_reader插件来读取通知的示例代码。notification_reader插件允许你访问和操作设备的通知。需要注意的是,由于访问通知通常涉及用户隐私,因此在实际应用中需要处理相关的权限请求。
1. 添加依赖
首先,在你的pubspec.yaml文件中添加notification_reader依赖:
dependencies:
  flutter:
    sdk: flutter
  notification_reader: ^最新版本号  # 请替换为最新版本号
然后运行flutter pub get来安装依赖。
2. 请求通知访问权限
在Android和iOS上,访问通知通常需要用户授权。你可以在应用的启动过程中请求这些权限。
Android
在AndroidManifest.xml中添加必要的权限:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">
    
    <uses-permission android:name="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"/>
    
    <!-- 其他配置 -->
    
</manifest>
iOS
在Info.plist中添加必要的配置,以请求通知访问权限。不过,iOS的通知访问权限通常是通过系统设置授予的,插件会自动处理这部分。
3. 使用notification_reader插件
下面是一个简单的示例,展示如何使用notification_reader插件来读取通知。
import 'package:flutter/material.dart';
import 'package:notification_reader/notification_reader.dart';
void main() {
  runApp(MyApp());
}
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
  NotificationReader? _notificationReader;
  List<NotificationData> _notifications = [];
  @override
  void initState() {
    super.initState();
    _initNotificationReader();
  }
  Future<void> _initNotificationReader() async {
    _notificationReader = NotificationReader();
    // 请求通知访问权限
    bool hasPermission = await _notificationReader!.requestNotificationPermission();
    if (hasPermission) {
      // 开始监听通知变化
      _notificationReader!.addNotificationListener((List<NotificationData> notifications) {
        setState(() {
          _notifications = notifications;
        });
      });
      // 获取当前通知
      List<NotificationData> currentNotifications = await _notificationReader!.getNotifications();
      setState(() {
        _notifications = currentNotifications;
      });
    } else {
      print("No permission to read notifications");
    }
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Notification Reader Example'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text('Notifications:', style: TextStyle(fontSize: 20)),
              SizedBox(height: 16),
              Expanded(
                child: ListView.builder(
                  itemCount: _notifications.length,
                  itemBuilder: (BuildContext context, int index) {
                    NotificationData notification = _notifications[index];
                    return ListTile(
                      title: Text('Title: ${notification.title}'),
                      subtitle: Text('Body: ${notification.body}'),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
  @override
  void dispose() {
    _notificationReader?.removeNotificationListener();
    super.dispose();
  }
}
注意事项
- 权限处理:在实际应用中,你需要更细致地处理权限请求的结果,比如向用户解释为什么需要这个权限,以及在权限被拒绝时提供引导。
 - 隐私政策:确保你的应用有明确的隐私政策,告知用户你的应用将如何使用这些通知数据。
 - 平台差异:不同平台在通知访问权限的处理上可能有所不同,务必根据平台文档进行相应调整。
 
这个示例代码展示了如何使用notification_reader插件来读取通知,并在Flutter应用中展示这些通知的标题和内容。希望这对你有帮助!
        
      
            
            
            
