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

Android(Kotlin)点击按钮发送通知失效问题求助

解决Android Kotlin通知无法触发且无权限提示问题

问题分析

你的代码存在几个关键问题,导致通知功能失效:

  • NotificationCompat.Builder未指定渠道ID,API26+系统要求通知必须关联已创建的渠道
  • Android 13+(API33)需要动态申请POST_NOTIFICATIONS权限,代码未处理该逻辑
  • 未确认目标Activity是否在Manifest中注册

修复步骤

1. 补全通知渠道ID

修改NotificationCompat.Builder的初始化代码,传入定义好的CHANNEL_ID:

var builder = NotificationCompat.Builder(this, CHANNEL_ID)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("New Notification🤩")
    .setContentText("this is a test")
    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
    .setContentIntent(pendingIntent)
    .setAutoCancel(true)

2. 添加并动态申请通知权限

  • 在AndroidManifest.xml中添加权限声明:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
  • 在init()方法中添加权限检查与申请逻辑:
@SuppressLint("MissingPermission")
fun init(){
    bindView()
    createNotificationChannel()
    
    // 针对Android 13+申请通知权限
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1001)
        }
    }
    
    btnNofig.setOnClickListener  {
        // 原有点击逻辑保持不变
    }
}
  • 可选:处理权限申请结果
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    if (requestCode == 1001) {
        if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // 权限已授予,可正常发送通知
        } else {
            // 权限被拒绝,可提示用户手动开启
        }
    }
}

3. 确认目标Activity已注册

打开AndroidManifest.xml,确保AlertDetailsActivity已注册:

<activity android:name=".AlertDetails" />

4. 检查通知图标资源

确保R.drawable.notification_icon是有效的通知图标(建议使用透明背景的单色图标),无效图标会导致通知无法显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 12:35:05