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

Android Studio中Kotlin实现Heads-up Notification(悬浮通知)问题

实现Android悬浮通知(Heads-up Notification)的代码修改方案

一、Notification.kt 核心修改

要实现悬浮通知,核心是提升通知优先级并配置触发条件,以下是修改后的完整代码:

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.PendingIntentCompat

class NotificationHelper(private val context: Context) {
    private val notificationManager: NotificationManager by lazy {
        context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    }
    private val CHANNEL_ID = "HEADS_UP_CHANNEL"
    private val CHANNEL_NAME = "悬浮通知渠道"

    init {
        createNotificationChannel()
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                CHANNEL_NAME,
                // Android 8.0+必须设置渠道高优先级,否则无法弹出悬浮
                NotificationManager.IMPORTANCE_HIGH
            ).apply {
                description = "用于显示悬浮式通知"
                enableVibration(true) // 振动是触发悬浮的条件之一
            }
            notificationManager.createNotificationChannel(channel)
        }
    }

    // 构建悬浮通知实例
    fun buildHeadsUpNotification(): Notification {
        return NotificationCompat.Builder(context, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_notification) // 替换成你的应用通知图标
            .setContentTitle("悬浮通知提醒")
            .setContentText("这是一条会悬浮在屏幕顶部的通知")
            .setPriority(NotificationCompat.PRIORITY_HIGH) // 兼容Android 7.0及以下版本
            .setDefaults(NotificationCompat.DEFAULT_VIBRATE) // 用振动触发悬浮,也可添加DEFAULT_SOUND
            .setAutoCancel(true) // 点击后自动取消通知
            // 可选:如果需要锁屏/前台也强制悬浮,添加全屏Intent
            // .setFullScreenIntent(getFullScreenPendingIntent(), true)
            .build()
    }

    // 可选:创建全屏Intent(用于强制触发悬浮)
    private fun getFullScreenPendingIntent() = PendingIntentCompat.getActivity(
        context,
        0,
        Intent(context, FullScreenNotificationActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        },
        PendingIntentCompat.FLAG_UPDATE_CURRENT or PendingIntentCompat.FLAG_IMMUTABLE,
        false
    )

    // 显示悬浮通知
    fun showHeadsUpNotification(notificationId: Int = 1) {
        notificationManager.notify(notificationId, buildHeadsUpNotification())
    }
}

关键修改点:

  • Android 8.0+ 通知渠道的importance设为IMPORTANCE_HIGH,这是悬浮通知的必要前提
  • 通知构建器设置PRIORITY_HIGH,兼容低版本系统
  • 添加振动/声音等触发条件,系统会根据这些高优先级行为弹出悬浮通知

二、MainActivity.kt 调用调整

把原来调用普通通知的逻辑,替换成调用悬浮通知的方法即可:

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val notificationHelper = NotificationHelper(this)
        // 示例:点击按钮触发悬浮通知
        findViewById<View>(R.id.btn_show_heads_up).setOnClickListener {
            notificationHelper.showHeadsUpNotification()
        }
    }
}

三、必须注意的细节

  1. 权限申请:Android 13+ 需要动态申请通知权限,先在Manifest里添加:
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    
    然后在代码中请求权限:
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && 
        ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1001)
    }
    
  2. 厂商系统限制:部分国产手机会默认关闭悬浮通知权限,需要引导用户到应用设置页面开启「悬浮通知」或「通知弹窗」权限
  3. 全屏Intent的使用:如果需要在锁屏状态或应用前台也强制弹出悬浮,需要创建一个透明的FullScreenNotificationActivity,并配置全屏Intent(代码中已注释,按需启用)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:40:25