Flutter通知监听插件notification_listener的使用
Flutter通知监听插件notification_listener的使用
安装和设置
1. 添加插件依赖
在 pubspec.yaml
文件中添加 notification_listener
插件依赖:
dependencies:
notification_listener: any # 替换为最新版本。
2. 在 AndroidManifest.xml
中声明服务
在 AndroidManifest.xml
文件中添加以下服务声明,以绑定通知服务与应用程序:
<service android:label="notifications" android:name="dev.tabhishekpaul.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. 请求通知访问权限
请求用户通过设置授予通知访问权限:
- 设置 → 应用和通知 → 特殊应用访问 → 通知访问。
使用示例
1. 检查通知权限
检查应用程序是否已获得通知访问权限:
import 'package:notification_listener/notification_listener.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
// 检查通知权限
final bool isGranted = await AndroidNotificationListener.isGranted();
if (isGranted) {
print('通知访问权限已授予!');
} else {
print('通知访问权限未授予。');
}
runApp(const MainScreen());
}
class MainScreen extends StatelessWidget {
const MainScreen({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
void initState() {
super.initState();
// 监听通知事件
AndroidNotificationListener.accessStream.listen((event) {
print("来自 ${event.packageName} 的通知: ${event.title}");
});
}
Future<void> requestPermission() async {
final bool granted = await AndroidNotificationListener.request();
if (granted) {
print('权限已授予!');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Notification Listener')),
body: Center(
child: ElevatedButton(
onPressed: () {
requestPermission();
},
child: Text('请求通知权限'),
),
),
);
}
}
2. 请求通知权限
打开通知设置页面并等待用户授予权限:
// 请求通知权限
final bool granted = await AndroidNotificationListener.request();
if (granted) {
print('权限已授予!');
}
3. 监听通知
监听传入的通知事件:
AndroidNotificationListener.accessStream.listen((event) {
print("来自 ${event.packageName} 的通知: ${event.title}");
});
4. 回复通知
向通知发送直接消息回复:
try {
await event.sendReply("这是一条自动回复。");
} catch (e) {
print('发送回复时出错: $e');
}
ServiceNotificationEvent
提供了以下属性:
id
: 通知ID。canReply
: 通知是否支持回复。haveExtraPicture
: 通知是否包含图片。hasRemoved
: 通知是否已被移除。packageName
: 发起通知的应用包名。title
: 通知标题。content
: 通知的主要内容。appIcon / extrasPicture / largeIcon
: 可用的显示图片。
更多关于Flutter通知监听插件notification_listener的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter通知监听插件notification_listener的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何在Flutter项目中使用notification_listener
插件来监听通知的示例代码。这个插件允许你的Flutter应用监听设备上的通知。
首先,确保你已经在pubspec.yaml
文件中添加了notification_listener
插件的依赖:
dependencies:
flutter:
sdk: flutter
notification_listener: ^0.x.x # 请替换为最新版本号
然后运行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.FOREGROUND_SERVICE"/>
<application
... >
<service
android:name=".NotificationListenerService"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
...
</application>
</manifest>
创建自定义的NotificationListenerService
由于notification_listener
插件需要一个自定义的NotificationListenerService
,你需要创建一个Java或Kotlin类来处理通知。这里以Kotlin为例:
在android/app/src/main/kotlin/com/example/yourapp/
目录下创建一个名为NotificationListenerService.kt
的文件:
package com.example.yourapp
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import android.util.Log
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.dart.DartExecutor
import io.flutter.plugin.common.MethodChannel
class NotificationListenerService : NotificationListenerService() {
private val CHANNEL = "com.example.yourapp/notification_listener"
override fun onCreate() {
super.onCreate()
MethodChannel(FlutterEngine(this).dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
// You can handle method calls from Dart here if needed
}
// Initialize the method channel for sending data to Dart
val methodChannel = MethodChannel(getFlutterEngine()?.dartExecutor?.binaryMessenger, CHANNEL)
setupNotificationListener(methodChannel)
}
private fun setupNotificationListener(channel: MethodChannel) {
val notificationListener = object : NotificationListener.Stub() {
override fun onNotificationPosted(sbn: StatusBarNotification) {
val packageName = sbn.packageName
val title = sbn.notification.extras.getString("android.title")
val text = sbn.notification.extras.getCharSequence("android.text").toString()
Log.d("NotificationListener", "Package: $packageName, Title: $title, Text: $text")
// Send the notification data to Dart
channel.invokeMethod("onNotificationPosted", mapOf(
"packageName" to packageName,
"title" to title,
"text" to text
))
}
override fun onNotificationRemoved(sbn: StatusBarNotification) {
// Handle notification removal if needed
}
}
this.registerAsNotificationListener(notificationListener)
}
override fun onDestroy() {
super.onDestroy()
// Unregister the notification listener if needed
}
}
Flutter端代码
现在,在你的Flutter项目中,你可以使用notification_listener
插件来请求通知监听权限并监听通知。
import 'package:flutter/material.dart';
import 'package:notification_listener/notification_listener.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool _isNotificationServiceEnabled = false;
@override
void initState() {
super.initState();
_requestNotificationListenerPermission();
}
Future<void> _requestNotificationListenerPermission() async {
bool status = await NotificationListener.checkPermissionStatus();
if (!status) {
bool granted = await NotificationListener.requestPermission();
if (granted) {
setState(() {
_isNotificationServiceEnabled = true;
});
_startListeningToNotifications();
}
} else {
setState(() {
_isNotificationServiceEnabled = true;
});
_startListeningToNotifications();
}
}
void _startListeningToNotifications() {
NotificationListener.notificationPosted.listen((notification) {
print("Notification received: ${notification['packageName']}, ${notification['title']}, ${notification['text']}");
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Notification Listener Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Notification Listener Permission Status: $_isNotificationServiceEnabled'),
],
),
),
),
);
}
}
注意事项
- 确保你的Android应用具有
NOTIFICATION_SERVICE
权限,并且用户已经授予该权限。 - 在实际使用中,你应该处理用户拒绝权限请求的情况。
notification_listener
插件在iOS上的支持有限,如果需要跨平台支持,你可能需要查找其他解决方案。
希望这能帮助你在Flutter项目中成功使用notification_listener
插件来监听通知!