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

如何检测用户是否授予应用POST_NOTIFICATIONS权限及开启通知设置?

如何检查应用的通知权限与系统通知设置状态

1. 检查POST_NOTIFICATIONS权限(Android 13+)

  • 从Android 13(API 33)起,POST_NOTIFICATIONS属于危险权限,需动态申请并检查;Android 12及以下版本无需此权限,默认具备通知发送权限。
  • 检查代码示例(Kotlin):
import android.content.Context
import android.os.Build
import android.Manifest
import android.content.pm.PackageManager
import androidx.core.content.ContextCompat

fun hasPostNotificationsPermission(context: Context): Boolean {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        ContextCompat.checkSelfPermission(
            context,
            Manifest.permission.POST_NOTIFICATIONS
        ) == PackageManager.PERMISSION_GRANTED
    } else {
        true
    }
}

2. 检查系统设置中应用通知的开启状态

  • 即便权限已授予,用户仍可能在系统设置中关闭应用通知总开关,需单独校验。
  • 检查代码示例(Kotlin):
import android.content.Context
import android.app.NotificationManager

fun isAppNotificationEnabled(context: Context): Boolean {
    val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    return notificationManager.areNotificationsEnabled()
}
  • 若需检查特定通知渠道的开启状态,可使用:
notificationManager.getNotificationChannel(channelId)?.importance != NotificationManager.IMPORTANCE_NONE

综合使用示例

fun checkNotificationStatus(context: Context) {
    val hasPermission = hasPostNotificationsPermission(context)
    val isNotificationEnabled = isAppNotificationEnabled(context)
    
    when {
        !hasPermission -> {
            // 触发POST_NOTIFICATIONS权限申请流程
        }
        !isNotificationEnabled -> {
            // 引导用户前往系统设置开启应用通知
        }
        else -> {
            // 权限与通知开关均正常,可发送通知
        }
    }
}
  • 引导用户跳转至应用通知设置页的代码:
import android.content.Intent
import android.provider.Settings

fun openAppNotificationSettings(context: Context) {
    val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).apply {
        putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
    }
    context.startActivity(intent)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 12:57:08