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

Android Studio中PendingIntent致应用崩溃且通知无响应问题求助

解决通知PendingIntent导致的应用崩溃问题

取消注释代码中那三行PendingIntent相关代码后,应用弹出通知随即崩溃,且点击通知无响应,问题出在直接修改已构建完成的Notification对象属性上:

NotificationCompat.Builder.build()方法返回的是一个不可变的Notification实例,此时直接给notification.contentIntent赋值会触发异常,导致应用崩溃。

正确的实现方式

应该在NotificationCompat.Builder的链式调用过程中,直接通过.setContentIntent()方法设置PendingIntent,而不是构建完成后再修改。

修改后的完整代码:

package com.example.notifsimple

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    val CHANNEL_ID = "channel_99"
    val id = 123456

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btnNotif.setOnClickListener{

            val importance = NotificationManager.IMPORTANCE_HIGH
            val mChannel = NotificationChannel(CHANNEL_ID, "اسم الفناه", importance)

            // 先创建PendingIntent
            val intent = Intent(this, MainActivity::class.java)
            val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)

            // 在Builder链式调用中设置contentIntent
            val notification = NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.android)
                .setContentTitle("New Animal")
                .setContentText("a new Cowala has been dicovered in the Amazons!")
                .setContentIntent(pendingIntent) // 在这里设置
                .build()

            val mNotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            mNotificationManager.createNotificationChannel(mChannel)

            mNotificationManager.notify(id, notification)
        }
    }
}

另外注意代码里的CHNANNEL_ID拼写错误,已经修正为CHANNEL_ID,避免后续可能出现的通道匹配问题。

内容的提问来源于stack exchange,提问作者Husam Abu Zina

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:50:51