![]() | ![]() |
|---|
通知是 Android 在您的应用 UI 之外显示的消息,用于向用户提供提醒、来自其他人的通信或来自您的应用的其他及时信息。用户可以点击通知打开您的应用或直接从通知中执行操作。
本文将带领实现各种常见的通知功能,以及各个Android版本需要做的适配。

NotificationManager 通知管理器,用来发起、更新、删除通知NotificationChannel 通知渠道,8.0及以上配置渠道以及优先级NotificationCompat.Builder 通知构造器,用来配置通知的布局显示以及操作相关常用API,查看第5节。
各版本适配,查看第6节。

private fun createNotificationForNormal() {
// 适配8.0及以上 创建渠道
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(mNormalChannelId, mNormalChannelName, NotificationManager.IMPORTANCE_LOW).apply {
description = "描述"
setShowBadge(false) // 是否在桌面显示角标
}
mManager.createNotificationChannel(channel)
}
// 点击意图 // setDeleteIntent 移除意图
val intent = Intent(this, MaterialButtonActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
// 构建配置
mBuilder = NotificationCompat.Builder(this@NotificationActivity, mNormalChannelId)
.setContentTitle("普通通知") // 标题
.setContentText("普通通知内容") // 文本
.setSmallIcon(R.mipmap.ic_launcher) // 小图标
.setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_avatar)) // 大图标
.setPriority(NotificationCompat.PRIORITY_DEFAULT) // 7.0 设置优先级
.setContentIntent(pendingIntent) // 跳转配置
.setAutoCancel(true) // 是否自动消失(点击)or mManager.cancel(mNormalNotificationId)、cancelAll、setTimeoutAfter()
// 发起通知
mManager.notify(mNormalNotificationId, mBuilder.build())
}
发起一个普通通知的几个要素:

重要通知,优先级设置最高,会直接显示在屏幕内(前台),而不是只有通知抽屉里,所以一定要谨慎设置,不要引起用户的负面情绪。
private fun createNotificationForHigh() {
val intent = Intent(this, MaterialButtonActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(mHighChannelId, mHighChannelName, NotificationManager.IMPORTANCE_HIGH)
channel.setShowBadge(true)
mManager.createNotificationChannel(channel)
}
mBuilder = NotificationCompat.Builder(this@NotificationActivity, mHighChannelId)
.setContentTitle("重要通知")
.setContentText("重要通知内容")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_avatar))
.setAutoCancel(true)
.setNumber(999) // 自定义桌面通知数量
.addAction(R.mipmap.ic_avatar, "去看看", pendingIntent)// 通知上的操作
.setCategory(NotificationCompat.CATEGORY_MESSAGE) // 通知类别,"勿扰模式"时系统会决定要不要显示你的通知
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE) // 屏幕可见性,锁屏时,显示icon和标题,内容隐藏
mManager.notify(mHighNotificationId, mBuilder.build())
}
这里有几个新增的配置:

可以通过addAction在通知上添加一个自定义操作,如上图:去看看。
可以通过PendingIntent打开一个Activity,也可以是发送一个广播。
在Android10.0及以上,系统也会默认识别并添加一些操作,比如短信通知上的「复制验证码」。


private fun createNotificationForProgress() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(mProgressChannelId, mProgressChannelName, NotificationManager.IMPORTANCE_DEFAULT)
mManager.createNotificationChannel(channel)
}
val progressMax = 100
val progressCurrent = 30
mBuilder = NotificationCompat.Builder(this@NotificationActivity, mProgressChannelId)
.setContentTitle("进度通知")
.setContentText("下载中:$progressCurrent%")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_avatar))
// 第3个参数indeterminate,false表示确定的进度,比如100,true表示不确定的进度,会一直显示进度动画,直到更新状态下载完成,或删除通知
.setProgress(progressMax, progressCurrent, false)
mManager.notify(mProgressNotificationId, mBuilder.build())
}
比较常见的就是下载进度了,比如应用内版本更新。
通过setProgress配置进度,接收3个参数:
如何更新进度往下看。

private fun updateNotificationForProgress() {
if (::mBuilder.isInitialized) {
val progressMax = 100
val progressCurrent = 50
// 1.更新进度
mBuilder.setContentText("下载中:$progressCurrent%").setProgress(progressMax, progressCurrent, false)
// 2.下载完成
//mBuilder.setContentText("下载完成!").setProgress(0, 0, false)
mManager.notify(mProgressNotificationId, mBuilder.build())
Toast.makeText(this, "已更新进度到$progressCurrent%", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "请先发一条进度条通知", Toast.LENGTH_SHORT).show()
}
}
更新进度也还是通过setProgress,修改当前进度值即可。
更新分为两种情况:
注意:如果有多个进度通知,如何更新到指定的通知,是通过NotificationId匹配的。
Author:yechaoa

private fun createNotificationForBigText() {
val bigText =
"A notification is a message that Android displays outside your app's UI to provide the user with reminders, communication from other people, or other timely information from your app. Users can tap the notification to open your app or take an action directly from the notification."
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(mBigTextChannelId, mBigTextChannelName, NotificationManager.IMPORTANCE_DEFAULT)
mManager.createNotificationChannel(channel)
}
mBuilder = NotificationCompat.Builder(this@NotificationActivity, mBigTextChannelId)
.setContentTitle("大文本通知")
.setStyle(NotificationCompat.BigTextStyle().bigText(bigText))
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_avatar))
.setAutoCancel(true)
mManager.notify(mBigTextNotificationId, mBuilder.build())
}
通知内容默认最多显示一行,超出会被裁剪,且无法展开,在内容透出上体验非常不好,展示的内容可能无法吸引用户去点击查看,所以也有了大文本通知的这种方式,
一劳永逸的做法就是无论内容有多少行,都用大文本的这种方式通知,具体展示让系统自己去适配。

private fun createNotificationForBigImage() {
val bigPic = BitmapFactory.decodeResource(resources, R.drawable.ic_big_pic)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(mBigImageChannelId, mBigImageChannelName, NotificationManager.IMPORTANCE_DEFAULT)
mManager.createNotificationChannel(channel)
}
mBuilder = NotificationCompat.Builder(this@NotificationActivity, mBigImageChannelId)
.setContentTitle("大图片通知")
.setContentText("有美女,展开看看")
.setStyle(NotificationCompat.BigPictureStyle().bigPicture(bigPic))
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_avatar))
.setAutoCancel(true)
mManager.notify(mBigImageNotificationId, mBuilder.build())
}
与大文本通知方式差不多
有一个注意的点,当已有多条通知时,默认是合并的,并不是展开的,所以可以通过setContentText("有美女,展开看看")加个提示。
3条,会展开3条,通知会聚合并折叠
private fun createNotificationForCustom() {
// 适配8.0及以上
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(mCustomChannelId, mCustomChannelName, NotificationManager.IMPORTANCE_DEFAULT)
mManager.createNotificationChannel(channel)
}
// 适配12.0及以上
mFlag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.FLAG_IMMUTABLE
} else {
PendingIntent.FLAG_UPDATE_CURRENT
}
// 添加自定义通知view
val views = RemoteViews(packageName, R.layout.layout_notification)
// 添加暂停继续事件
val intentStop = Intent(mStopAction)
val pendingIntentStop = PendingIntent.getBroadcast(this@NotificationActivity, 0, intentStop, mFlag)
views.setOnClickPendingIntent(R.id.btn_stop, pendingIntentStop)
// 添加完成事件
val intentDone = Intent(mDoneAction)
val pendingIntentDone = PendingIntent.getBroadcast(this@NotificationActivity, 0, intentDone, mFlag)
views.setOnClickPendingIntent(R.id.btn_done, pendingIntentDone)
// 创建Builder
mBuilder = NotificationCompat.Builder(this@NotificationActivity, mCustomChannelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_avatar))
.setAutoCancel(true)
.setCustomContentView(views)
.setCustomBigContentView(views)// 设置自定义通知view
// 发起通知
mManager.notify(mCustomNotificationId, mBuilder.build())
}
假如是一个播放器的前台通知,默认的布局显示已经不满足需求,那么就用到自定义布局了。
通过RemoteViews构建自定义布局view。因为RemoteViews并不是一个真正的view,它只是一个view的描述,所以事件处理上还是要借助PendingIntent。
折叠状态下,可能会展示一些基础信息,拿播放器举例,比如当前歌曲名称、歌手、暂停、继续、下一首等,就差不多展示不下了。
展开状态下,就可以提供更多的信息,比如专辑信息,歌手信息等
这两种状态下默认的布局高度:
48dp252dp
private fun updateNotificationForCustom() {
// 发送通知 更新状态及UI
sendBroadcast(Intent(mStopAction))
}
private fun updateCustomView() {
val views = RemoteViews(packageName, R.layout.layout_notification)
val intentUpdate = Intent(mStopAction)
val pendingIntentUpdate = PendingIntent.getBroadcast(this, 0, intentUpdate, mFlag)
views.setOnClickPendingIntent(R.id.btn_stop, pendingIntentUpdate)
// 根据状态更新UI
if (mIsStop) {
views.setTextViewText(R.id.tv_status, "那些你很冒险的梦-停止播放")
views.setTextViewText(R.id.btn_stop, "继续")
mBinding.mbUpdateCustom.text = "继续"
} else {
views.setTextViewText(R.id.tv_status, "那些你很冒险的梦-正在播放")
views.setTextViewText(R.id.btn_stop, "暂停")
mBinding.mbUpdateCustom.text = "暂停"
}
mBuilder.setCustomContentView(views).setCustomBigContentView(views)
// 重新发起通知更新UI,注意:必须得是同一个通知id,即mCustomNotificationId
mManager.notify(mCustomNotificationId, mBuilder.build())
}
上面提到,因为RemoteViews并不能直接操作view,所以可以通过广播的方式,对该条通知的构建配置重新设置,以达到更新的效果。
远古时期v4包里还有MediaStyle,AndroidX已经下掉了。
| API | 描述 |
|---|---|
| setContentTitle | 标题 |
| setContentText | 内容 |
| setSubText | 子标题 |
| setLargeIcon | 大图标 |
| setSmallIcon | 小图标 |
| setContentIntent | 点击时意图 |
| setDeleteIntent | 删除时意图 |
| setFullScreenIntent | 全屏通知点击意图,来电、响铃 |
| setAutoCancel | 点击自动取消 |
| setCategory | 通知类别,适用“勿扰模式” |
| setVisibility | 屏幕可见性,适用“锁屏状态” |
| setNumber | 通知项数量 |
| setWhen | 通知时间 |
| setShowWhen | 是否显示通知时间 |
| setSound | 提示音 |
| setVibrate | 震动 |
| setLights | 呼吸灯 |
| setPriority | 优先级,7.0 |
| setTimeoutAfter | 定时取消,8.0及以后 |
| setProgress | 进度 |
| setStyle | 通知样式,BigPictureStyle、BigTextStyle、MessagingStyle、InboxStyle、DecoratedCustomViewStyle |
| addAction | 通知上的操作,10.0 |
| setGroup | 分组 |
| setColor | 背景颜色 |
自Android 4.0支持通知以来,几乎每个版本都有各种改动,也是苦了开发了…
Android 5.0开始,支持重要通知,也称抬头通知。
Android 5.0开始,支持锁屏通知,即锁屏时显示在锁屏桌面。
从8.0开始,用户可以通过通知渠道设置启用或禁止锁屏通知…
5.0开始,勿扰模式下会组织所有声音和震动,8.0以后可以根据渠道分别设置。
7.1及以下:
mBuilder = NotificationCompat.Builder(this@NotificationActivity, mNormalChannelId)
...
.setPriority(NotificationCompat.PRIORITY_DEFAULT) // 7.0 设置优先级
8.0及以上改为渠道。
7.0引入直接回复操作的功能
private val KEY_TEXT_REPLY = "key_text_reply"
var replyLabel: String = resources.getString(R.string.reply_label)
var remoteInput: RemoteInput = RemoteInput.Builder(KEY_TEXT_REPLY).run {
setLabel(replyLabel)
build()
}
7.0开始支持消息类型通知MessagingStyle
var notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setStyle(NotificationCompat.MessagingStyle("Me")
.setConversationTitle("Team lunch")
.addMessage("Hi", timestamp1, null) // Pass in null for user.
.addMessage("What's up?", timestamp2, "Coworker")
.addMessage("Not much", timestamp3, null)
.addMessage("How about lunch?", timestamp4, "Coworker"))
.build()
从8.0开始,消息类型的展示方式为折叠类型…
7.0开始,通知支持分组,适用多个通知的情况。
创建通知渠道,以及重要性
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(mHighChannelId, mHighChannelName, NotificationManager.IMPORTANCE_HIGH)
mManager.createNotificationChannel(channel)
}
删除渠道
notificationManager.deleteNotificationChannel(id)
8.0开始,支持设置通知时桌面的角标是否显示
val mChannel = NotificationChannel(id, name, importance).apply {
description = descriptionText
setShowBadge(false)
}
8.1开始,每秒发出的通知声音不能超过一次。
8.0开始,设置通知的背景颜色。
mBuilder = NotificationCompat.Builder(this@NotificationActivity, mHighChannelId)
...
.addAction(R.mipmap.ic_avatar, "去看看", pendingIntent)// 通知上的操作
10.0全屏意图需要在manifest中申请USE_FULL_SCREEN_INTENT权限
12.0及以上,可以设置需要解锁设备才能操作:setAuthenticationRequired
val moreSecureNotification = Notification.Builder(context, NotificationListenerVerifierActivity.TAG)
.addAction(...)
// from a lock screen.
.setAuthenticationRequired(true)
.build()
从12.0开始,将不支持完全自定义的通知,会提供 Notification.DecoratedCustomViewStyle替代…
12.0需要明确设置flag,否则会有报错:
java.lang.IllegalArgumentException: com.example.imdemo: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
mFlag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.FLAG_IMMUTABLE
} else {
PendingIntent.FLAG_UPDATE_CURRENT
}
val intentStop = Intent(mStopAction)
val pendingIntentStop = PendingIntent.getBroadcast(this@NotificationActivity, 0, intentStop, mFlag)
views.setOnClickPendingIntent(R.id.btn_stop, pendingIntentStop)
梳理完适配,真的觉得Androider苦😭
https://github.com/yechaoa/MaterialDesign
代码也有详细的注释,欢迎star
写作不易,感谢点赞支持 ^ - ^
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h