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

Android如何实现特定应用通知访问过滤 适配API Level 30以下版本

Android 跨版本特定应用通知过滤实现方案

核心逻辑依赖Android系统公开的NotificationListenerService组件,该组件从API 18(Android 4.3)开始提供,最低可兼容到Android 4.3版本,覆盖市面上绝大多数仍在运营的Android设备。API 30新增的系统级拦截API仅为优化实现,更低版本可通过监听通知回调后自行处理过滤逻辑实现等价效果。

1. 全版本通用基础配置

1.1 注册通知监听服务

在AndroidManifest.xml中添加服务注册声明:

<service
    android:name=".CustomNotificationListener"
    android:label="通知访问服务"
    android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
    <intent-filter>
        <action android:name="android.service.notification.NotificationListenerService" />
    </intent-filter>
</service>

1.2 权限跳转与校验

  • 引导用户开启通知访问权限的兼容代码:
fun openNotificationPermissionPage(context: Context) {
    try {
        // 多数系统通用的通知权限设置页跳转
        context.startActivity(Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"))
    } catch (e: Exception) {
        // 异常情况兜底,跳转到应用详情页
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data = Uri.fromParts("package", context.packageName, null)
        context.startActivity(intent)
    }
}
  • 权限状态校验代码:
fun hasNotificationAccessPermission(context: Context): Boolean {
    val enabledListeners = Settings.Secure.getString(
        context.contentResolver,
        "enabled_notification_listeners"
    )
    return enabledListeners?.contains(context.packageName) == true
}

2. 分版本过滤逻辑实现

2.1 API 30及以上版本

可直接使用原有系统级拦截API,在系统层面完成通知过滤,无需处理通知回调。

2.2 API 18 ~ API 29版本

重写NotificationListenerService的onNotificationPosted回调,收到通知后判断包名是否为目标过滤应用,匹配后主动移除通知即可实现过滤效果:

class CustomNotificationListener : NotificationListenerService() {
    // 可自行配置需要过滤的应用包名列表
    private val blockedPackageSet = setOf("com.example.target.app1", "com.example.target.app2")

    override fun onNotificationPosted(sbn: StatusBarNotification?) {
        super.onNotificationPosted(sbn)
        sbn ?: return
        // 匹配过滤应用包名
        if (blockedPackageSet.contains(sbn.packageName)) {
            // 移除对应通知
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                cancelNotification(sbn.key)
            } else {
                // 适配API 18~20的取消方法
                cancelNotification(sbn.packageName, sbn.tag, sbn.id)
            }
            // 可选:如果需要留存通知数据,可在此处将通知信息存入本地存储
        }
    }
}

注意:该方式实现的过滤效果和API 30系统级拦截基本一致,仅会存在毫秒级的通知展示延迟,普通用户无感知。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 17:18:03