You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用React Native实现手机通知拦截与记录功能?

Android平台实现通知拦截与记录方案

核心思路

Android系统提供NotificationListenerService组件,专门用于监听系统通知的发布与清除事件,这是实现通知拦截记录的核心途径。

步骤1:申请通知访问权限

首先得引导用户开启通知访问权限,这是监听通知的前提:

  • 在Manifest中声明权限:
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
  • 跳转系统设置页面让用户授权:
val intent = Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS")
startActivity(intent)

步骤2:实现NotificationListenerService

创建自定义服务继承NotificationListenerService,重写关键方法处理通知事件:

class NotificationMonitorService : NotificationListenerService() {
    // 新通知发布时触发
    override fun onNotificationPosted(sbn: StatusBarNotification) {
        super.onNotificationPosted(sbn)
        // 提取通知核心信息
        val packageName = sbn.packageName // 发通知的APP包名
        val title = sbn.notification.extras.getString(Notification.EXTRA_TITLE) ?: ""
        val content = sbn.notification.extras.getString(Notification.EXTRA_TEXT) ?: ""
        val postTime = sbn.postTime // 通知发布时间戳
        val isClearable = sbn.isClearable // 是否可清除

        // 把信息存到本地(比如Room数据库、SharedPreferences)
        saveNotificationToLocal(packageName, title, content, postTime, isClearable)
    }

    // 通知被清除时触发(可选,用于记录移除事件)
    override fun onNotificationRemoved(sbn: StatusBarNotification) {
        super.onNotificationRemoved(sbn)
        // 标记本地记录为已清除
        markNotificationAsRemoved(sbn.key)
    }
}
  • 在Manifest中注册服务:
<service
    android:name=".NotificationMonitorService"
    android:label="通知历史监听服务"
    android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
    <intent-filter>
        <action android:name="android.service.notification.NotificationListenerService" />
    </intent-filter>
</service>

步骤3:存储通知数据

根据需求选合适的存储方式:

  • 轻量场景:用SharedPreferences存简单通知列表(适合少量数据)
  • 大量数据场景:用Room数据库存储,支持复杂查询、分页等功能(推荐)

注意事项

  • Android 13+:除了通知访问权限,还需申请POST_NOTIFICATIONS权限,但不影响监听其他APP通知。
  • 自定义通知兼容:部分APP用自定义布局,EXTRA_TITLE和EXTRA_TEXT可能拿不到完整内容,需额外解析RemoteViews(难度较高,要针对性处理)。
  • 服务保活:系统可能杀死后台服务,可通过前台服务、WorkManager等方式提高存活率。

iOS平台限制说明

iOS出于隐私保护,不允许第三方APP拦截或监听其他APP的推送通知:

  • 只能记录自己APP接收的推送,通过UNUserNotificationCenterDelegate方法处理。
  • 可使用Notification Service Extension修改自己APP的推送内容,但无法获取其他APP的通知数据。

内容的提问来源于stack exchange,提问作者prodohsamuel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 14:40:29