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

Android通知无法显示求助(基于Android Studio与Kotlin开发)

解决Android通知无法显示的问题

问题根源

Android 8.0(API Level 26)及更高版本强制要求所有通知必须关联一个通知渠道,你的代码仅构建了通知实例,但未创建对应CHANNEL_ID的渠道,系统会直接拦截无渠道的通知,导致无法显示。

修复方案

在发送通知前先创建对应的通知渠道,修改MainActivity代码如下:

修改后的完整代码

class MainActivity : AppCompatActivity() {
    companion object {
        const val NOTIFICATION_ID = 101
        const val CHANNEL_ID = "channelID"
        const val CHANNEL_NAME = "测试通知渠道"
        const val CHANNEL_DESCRIPTION = "用于展示应用测试通知"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        // 初始化通知渠道(仅API 26+需要)
        createNotificationChannel()

        val button : Button = findViewById(R.id.button_notification)
        button.setOnClickListener {
            val builder = NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Notification")
                .setContentText("Go ahead")
                .setPriority(Notification.PRIORITY_HIGH)
                .setAutoCancel(true)

            val notificationManager = NotificationManagerCompat.from(this)
            notificationManager.notify(NOTIFICATION_ID, builder.build())
        }
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 创建渠道实例,设置重要性与描述
            val channel = NotificationChannel(
                CHANNEL_ID,
                CHANNEL_NAME,
                NotificationManager.IMPORTANCE_HIGH
            ).apply {
                description = CHANNEL_DESCRIPTION
            }
            // 向系统注册渠道
            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
        }
    }
}

额外注意事项

  • 若测试设备为Android 13(API Level 33)及以上,需在AndroidManifest.xml中添加通知权限:
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    
    并在代码中动态申请该权限,用户授权后通知才能正常显示。
  • 确保setSmallIcon使用的图标符合系统规范,避免因图标格式/尺寸问题导致通知不展示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 21:05:20