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

Kotlin 自定义通知布局TextView绑定点击停止音频事件实现方案

实现自定义通知控件点击停止音频的方案

当使用setCustomContentView/setCustomBigContentView完全自定义通知布局时,系统默认的操作按钮区域会被替换,因此addAction添加的按钮不会展示,需要手动给自定义布局内的控件绑定点击事件,具体实现方式如下:

  • 第一步:适配高版本Android的PendingIntent规则
    Android 12(API 31)及以上系统要求PendingIntent必须明确指定可变性,否则会触发崩溃。将原有PendingIntent构造代码的Flag参数替换为PendingIntent.FLAG_IMMUTABLE(不需要修改Intent内容时使用,安全性更高):
val snoozeIntent = Intent(this, StopAlarm::class.java)
val snoozePendingIntent = PendingIntent.getBroadcast(this, 0, snoozeIntent, PendingIntent.FLAG_IMMUTABLE)
val notificationIntent = Intent(this, FullAzan::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE)
  • 第二步:给自定义布局的停止控件绑定点击事件
    通过RemoteViews.setOnClickPendingIntent方法,将停止广播的PendingIntent绑定到id为text_view_collapsed_3的TextView上:
expandedView.setTextViewText(R.id.text_view_collapsed_2, "Muazzin - ${nextPray.moazin}")
// 新增绑定停止按钮点击事件
expandedView.setOnClickPendingIntent(R.id.text_view_collapsed_3, snoozePendingIntent)
// 如果折叠状态的布局notification_collapsed中也包含该停止控件,同步添加绑定
// collapsedView.setOnClickPendingIntent(R.id.text_view_collapsed_3, snoozePendingIntent)
  • 可选补充:点击后自动关闭通知
    如果需要用户点击停止按钮后自动移除通知,可以在StopAlarm广播的onReceive逻辑中添加取消通知的代码:
override fun onReceive(context: Context, intent: Intent?) {
    // 原有停止音频、停止振动等逻辑保留
    // 取消对应id的通知
    NotificationManagerCompat.from(context).cancel(100)
}

原有不再生效的addAction相关代码可以直接删除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 17:45:02