Android 通知用法详解

Android 通知(Notification)完全指南

记得在测试APP的通知功能时,要在手机上把关于通知的权限打开!!!

1. 通知的作用

  • 用户提示:告知用户重要事件,如新消息、下载进度等。
  • 交互入口:用户点击通知可跳转至应用的特定页面。
  • 持续展示:某些通知需要常驻状态栏,如后台任务提醒。

2. 关键组件

  • NotificationManager:管理通知的发布、更新、取消。
  • NotificationCompat.Builder:构建通知,确保兼容低版本 Android。
  • NotificationChannel(Android 8.0+) :管理通知的重要性、声音、震动等。
  • PendingIntent:设定用户点击通知后的操作。

3. 创建通知

3.0 权限

在 AndroidManifest.xml 添加权限:

ini 复制代码
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>

3.1 创建通知频道(Android 8.0+ 必须)

ini 复制代码
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    val channelId = "channel_id_example"
    val channelName = "通知频道"
    val importance = NotificationManager.IMPORTANCE_DEFAULT
    val channel = NotificationChannel(channelId, channelName, importance).apply {
        description = "这个频道用于普通通知"
    }
    /*val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager这个写法和下面一行本质一样的,下面的更简洁安全,上面的能兼容旧版本(适用API22以及更早版本)*/
    val notificationManager = getSystemService(NotificationManager::class.java)
    notificationManager.createNotificationChannel(channel)
}

3.2 发送基础通知

kotlin 复制代码
val channelId = "channel_id_example"
val builder = NotificationCompat.Builder(this, channelId)
    .setSmallIcon(R.drawable.ic_notification)
    .setContentTitle("通知标题")
    .setContentText("通知内容")
    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
​
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(1, builder.build())/*通过 NotificationManager 显示通知。1 作为通知的 唯一 ID,用于标识和更新/取消特定通知。builder.build() 构建通知对象 并发送。*/

4. 添加交互(PendingIntent)

4.1 点击通知跳转到 Activity

创建一个 TargetActivity 作为跳转目标:

kotlin 复制代码
class TargetActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_target)
    }
}

修改通知代码,添加 PendingIntent:

kotlin 复制代码
val intent = Intent(this, TargetActivity::class.java)
val pendingIntent = PendingIntent.getActivity(
    this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
​
val builder = NotificationCompat.Builder(this, channelId)
    .setSmallIcon(R.drawable.ic_notification)
    .setContentTitle("点击查看详情")
    .setContentText("点击此通知跳转到 TargetActivity")
    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
    .setContentIntent(pendingIntent)
    .setAutoCancel(true) // 用户点击后自动清除通知
​
notificationManager.notify(2, builder.build())

5. 丰富通知内容(setStyle)

5.1 长文本通知(BigTextStyle)

less 复制代码
builder.setStyle(NotificationCompat.BigTextStyle()
    .bigText("这里是详细的通知内容,适合展示更多的文字信息"))

5.2 大图通知(BigPictureStyle)

less 复制代码
val bigPicture = BitmapFactory.decodeResource(resources, R.drawable.big_image)
builder.setStyle(NotificationCompat.BigPictureStyle()
    .bigPicture(bigPicture)
    .setBigContentTitle("大图通知"))

5.3 多条信息通知(InboxStyle)

less 复制代码
builder.setStyle(NotificationCompat.InboxStyle()
    .addLine("第一条信息")
    .addLine("第二条信息")
    .setSummaryText("共2条信息"))

6. 高级用法

  • 自定义通知布局 :使用 RemoteViews 创建个性化界面。
  • 前台服务通知:后台任务运行时显示不可清除的通知。
  • 分组通知:合并多个相关通知,减少干扰。

7. 重要注意事项

  • Android 8.0+ 必须使用 NotificationChannel,否则通知不会显示。
  • 使用 NotificationCompat 确保低版本 Android 兼容性。
  • 合理管理通知,避免频繁弹出影响用户体验。

总结

通过 NotificationManager 发送通知,使用 PendingIntent 响应点击操作,并通过 setStyle 增强通知的可读性和交互性。在 Android 8.0 及以上版本,必须创建 NotificationChannel,确保通知正常显示。结合这些技巧,可以打造更优雅、实用的通知系统。 🚀

相关推荐
骑着蜗牛撵大象32727 分钟前
豆包 Seed 驱动的记账智能体:从拍票抽取到月报生成的全链路落地记录
java·前端·javascript·结构化输出·豆包seed·多模态识别·记账系统
溪语流沙28 分钟前
【Web全栈进阶】前端世界观:现代工具链与框架为什么存在
前端·javascript·vue.js
kyriewen1 小时前
我逐个测了 JSON.stringify 的 7 个坑:第 1 个就在丢数据
前端·javascript·程序员
积流成海1 小时前
用代码实现哈希计算器:Web Crypto API 实战
前端·算法·哈希算法·哈希函数·盘子工具站
data analyse 4561 小时前
服务端访问日志聚合 PV 与 UV 怎么实现?日志采集与口径设计
大数据·前端·数据分析
JavaGuide1 小时前
DeepSeek Harness 重磅更新,Codex、Claude Code 子智能体进官方插件列表了,还有 Git 工作树和思考翻译!
前端·后端
小羊没烦恼!2 小时前
OS X 上使用.NET开发应用程序
开发语言·前端·数据库·人工智能·c#·策略模式
Eiceblue3 小时前
使用 Python 实现 Excel 行列转置(保留单元格样式)
前端·python·excel
西西学代码3 小时前
像素和颜色之间的转换(Flutter)
前端·javascript·flutter
茶底世界之下3 小时前
羽毛颜色已经很鲜艳,还要继续加色吗?用 Awaking 试一次减饱和
前端·ios·运营