Flutter通知监听插件skm_notification_listener的使用

发布于 1周前 作者 wuwangju 来自 Flutter

Flutter通知监听插件skm_notification_listener的使用

插件介绍

skm_notification_listener 是一个用于与 Android 通知服务进行交互的 Flutter 插件。它允许您监听系统发送的新通知或移除的通知。

安装和使用

1 添加依赖项

dependencies:
  skm_notification_listener: any # 或者在 Pub 上获取最新版本

2 在 AndroidManifest 中绑定通知服务

<service
    android:label="notifications"
    android:name="skm.notification_listener.skm_notification_listener.NotificationListener"
    android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"
    android:exported="true">
    <intent-filter>
        <action android:name="android.service.notification.NotificationListenerService" />
    </intent-filter>
</service>

3 使用示例代码

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

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

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  StreamSubscription<ServiceNotificationEvent>? _subscription;
  List<ServiceNotificationEvent> events = [];

  void log(String message) {
    print(message);
  }

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            children: [
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    TextButton(
                      onPressed: () async {
                        final res =
                            await SkmNotificationListener.requestPermission();
                        log("Is enabled: $res");
                      },
                      child: const Text("Request Permission"),
                    ),
                    const SizedBox(height: 20.0),
                    TextButton(
                      onPressed: () async {
                        final bool res =
                            await SkmNotificationListener.isPermissionGranted();
                        log("Is enabled: $res");
                      },
                      child: const Text("Check Permission"),
                    ),
                    const SizedBox(height: 20.0),
                    TextButton(
                      onPressed: () {
                        _subscription = SkmNotificationListener.notificationsStream.listen((event) {
                          log("$event");
                          setState(() {
                            events.add(event);
                          });
                        });
                      },
                      child: const Text("Start Stream"),
                    ),
                    const SizedBox(height: 20.0),
                    TextButton(
                      onPressed: () {
                        _subscription?.cancel();
                      },
                      child: const Text("Stop Stream"),
                    ),
                  ],
                ),
              ),
              Expanded(
                child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: events.length,
                  itemBuilder: (_, index) =&gt; Padding(
                    padding: const EdgeInsets.only(bottom: 8.0),
                    child: ListTile(
                      onTap: () async {
                        try {
                          await events[index]
                              .sendReply("This is an auto response");
                        } catch (e) {
                          log(e.toString());
                        }
                      },
                      trailing: events[index].hasRemoved!
                          ? const Text(
                              "Removed",
                              style: TextStyle(color: Colors.red),
                            )
                          : const SizedBox.shrink(),
                      leading: event[index].appIcon == null
                          ? const SizedBox.shrink()
                          : Image.memory(
                              event[index].appIcon!,
                              width: 35.0,
                              height: 35.0,
                            ),
                      title: Text(event[index].title ?? "No title"),
                      subtitle: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            event[index].content ?? "no content",
                            style: const TextStyle(fontWeight: FontWeight.bold),
                          ),
                          Text(
                            event[index].packageName ?? "no package name",
                            style: const TextStyle(fontWeight: FontWeight.bold),
                          ),
                          const SizedBox(height: 8.0),
                          event[index].canReply!
                              ? const Text(
                                  "Replied with: This is an auto reply",
                                  style: TextStyle(color: Colors.purple),
                                )
                              : const SizedBox.shrink(),
                          event[index].largeIcon != null
                              ? Image.memory(
                                  event[index].largeIcon!,
                                )
                              : const SizedBox.shrink(),
                        ],
                      ),
                      isThreeLine: true,
                    ),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用skm_notification_listener插件来监听通知的示例代码。

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

dependencies:
  flutter:
    sdk: flutter
  skm_notification_listener: ^最新版本号 # 替换为插件的实际最新版本号

然后,运行flutter pub get来安装依赖。

接下来,你需要进行一些配置,特别是Android平台上的配置。在android/app/src/main/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" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <application
        ...>

        <!-- Notification Listener Service Declaration -->
        <service
            android:name=".NotificationListenerServiceImplementation"
            android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
            <intent-filter>
                <action android:name="android.service.notification.NotificationListenerService" />
            </intent-filter>
        </service>

        ...
    </application>
</manifest>

注意:NotificationListenerServiceImplementation是你在Kotlin或Java中创建的类,这个类需要继承自NotificationListenerService。不过,skm_notification_listener插件可能已经为你处理了大部分这些配置,你只需确保权限和服务声明存在。

接下来,在Flutter代码中设置和使用skm_notification_listener插件:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Notification Listener Example'),
        ),
        body: NotificationListenerPage(),
      ),
    );
  }
}

class NotificationListenerPage extends StatefulWidget {
  @override
  _NotificationListenerPageState createState() => _NotificationListenerPageState();
}

class _NotificationListenerPageState extends State<NotificationListenerPage> {
  String _notificationMessage = '';

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

  void _startNotificationListener() async {
    SkmNotificationListener.notificationListener().listen((event) {
      setState(() {
        _notificationMessage = "Received Notification: ${event.packageName} - ${event.notification.title} - ${event.notification.body}";
      });
    });

    // 请求通知访问权限
    SkmNotificationListener.requestNotificationListenerPermission().then((granted) {
      if (granted) {
        print("Notification listener permission granted.");
      } else {
        print("Notification listener permission denied.");
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            'Notification Listener',
            style: TextStyle(fontSize: 24),
          ),
          SizedBox(height: 20),
          Text(
            _notificationMessage,
            style: TextStyle(fontSize: 18),
          ),
        ],
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,它使用skm_notification_listener插件来监听通知。当收到通知时,我们会更新UI以显示通知的详细信息。

请确保你已经按照插件的文档完成了所有必要的配置,包括在Android平台上请求并处理权限。此外,由于插件和Flutter框架的不断更新,请务必参考skm_notification_listener插件的最新文档和示例代码,以确保兼容性和最佳实践。

回到顶部