当前位置:网站首页>Notification uses full resolution
Notification uses full resolution
2022-07-07 15:58:00 【Sharp surge】
1、 effect
2、 brief introduction
Notice is Android In your app UI Messages displayed outside , Used to provide reminders to users 、 Communications from others or other timely information from your app . Users can click the notification to open your application or directly perform actions from the notification .
2.1、 Exhibition
- Notifications are displayed to users in different locations and formats , For example, the icon in the status bar 、 Notify more detailed entries in the drawer 、 Badges on app icons and wearable devices that are automatically paired .
- When notice is given , It first appears as an icon in the status bar .
2.2、 operation
- Users can slide down the status bar to open the notification drawer , There they can view more details and take action based on the notification .
- The user can drag down the notification in the drawer to display the expanded view , This view shows other content and action buttons ( Provided ).
- Notices remain visible in the notice drawer , Until it is closed by the application or user .
3、 Functional disassembly
This article will lead you through the implementation of various common notification functions , And each Android What the version needs to do adapter
.
4、 Function realization
4.0、 The key class
NotificationManager
Notification manager , Used to initiate 、 to update 、 Delete notificationNotificationChannel
Notification channels ,8.0 And above to configure channels and prioritiesNotificationCompat.Builder
Notify the constructor , It is used to configure the layout display of notifications and related operations
Commonly used API, Look at the first 5 section . Each version fits , Look at the first 6 section .
4.1、 General notice
private fun createNotificationForNormal() {
// adapter 8.0 And above Create channels
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(mNormalChannelId, mNormalChannelName, NotificationManager.IMPORTANCE_LOW).apply {
description = " describe "
setShowBadge(false) // Whether to display corner marks on the desktop
}
mManager.createNotificationChannel(channel)
}
// Click intent // setDeleteIntent Remove intent
val intent = Intent(this, MaterialButtonActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
// Building configuration
mBuilder = NotificationCompat.Builder([email protected], mNormalChannelId)
.setContentTitle(" General notice ") // title
.setContentText(" General notice content ") // Text
.setSmallIcon(R.mipmap.ic_launcher) // Small icons
.setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_avatar)) // Large icon
.setPriority(NotificationCompat.PRIORITY_DEFAULT) // 7.0 set priority
.setContentIntent(pendingIntent) // Jump configuration
.setAutoCancel(true) // Whether to disappear automatically ( Click on )or mManager.cancel(mNormalNotificationId)、cancelAll、setTimeoutAfter()
// Initiation notice
mManager.notify(mNormalNotificationId, mBuilder.build())
}
Several elements of initiating a general notification :
- setContentTitle title
- setContentText Content
- setSmallIcon Small icons
- setLargeIcon Large icon
- setPriority priority or Importance (7.0 and 8.0 In different ways )
- setContentIntent Click intent
- setAutoCancel Whether to cancel automatically
- notify Initiation notice
4.2、 Important notice
Important notice , The priority setting is the highest , Will be displayed directly on the screen ( The front desk ), Not just the notice drawer , So be sure to cautious
Set up , Do not cause negative emotions of users .
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([email protected], mHighChannelId)
.setContentTitle(" Important notice ")
.setContentText(" Important notice contents ")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_avatar))
.setAutoCancel(true)
.setNumber(999) // Customize the number of desktop notifications
.addAction(R.mipmap.ic_avatar, " Go to see ", pendingIntent)// Actions on notifications
.setCategory(NotificationCompat.CATEGORY_MESSAGE) // Notification category ," Don't disturb mode " The system will decide whether to display your notification
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE) // Screen visibility , When the screen is locked , Show icon And the title , Content hiding
mManager.notify(mHighNotificationId, mBuilder.build())
}
Here are a few new configurations :
- setNumber Number of desktop notifications
- addAction Actions on notifications
- setCategory Notification category ," Don't disturb mode " The system will decide whether to display your notification
- setVisibility Screen visibility , When the screen is locked , Show icon And the title , Content hiding , Unlock to view all
4.2.1、 Actions on notifications
Can pass addAction
Add a custom action to the notification , Pictured above : Go to see .
Can pass PendingIntent
Open one Activity, You can also send a broadcast .
stay Android10.0
And above , The system will also recognize and add some operations by default , For example, on the SMS notification 「 Copy verification code 」.
4.2.2、 Importance level
- emergency : Sound and display as a reminder notification
- high : Make a sound
- in : No sound
- low : No sound and does not appear in the status bar
4.3、 Progress bar notification
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([email protected], mProgressChannelId)
.setContentTitle(" Progress notification ")
.setContentText(" In the download :$progressCurrent%")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_avatar))
// The first 3 Parameters indeterminate,false Indicates the determined progress , such as 100,true Indicates an uncertain progress , Progress animation will always be displayed , Until the update status download is complete , Or delete the notification
.setProgress(progressMax, progressCurrent, false)
mManager.notify(mProgressNotificationId, mBuilder.build())
}
The most common is the download progress , For example, in app version update .
adopt setProgress
Configuration progress , receive 3 Parameters :
- max Maximum
- progress Current progress
- indeterminate false Indicates the determined progress , such as 100,true Indicates an uncertain progress , Progress animation will always be displayed , Until the update status is complete , Or delete the notification
How to update progress and look down .
4.4、 Update progress bar notifications
private fun updateNotificationForProgress() {
if (::mBuilder.isInitialized) {
val progressMax = 100
val progressCurrent = 50
// 1. Update progress
mBuilder.setContentText(" In the download :$progressCurrent%").setProgress(progressMax, progressCurrent, false)
// 2. Download complete
//mBuilder.setContentText(" Download complete !").setProgress(0, 0, false)
mManager.notify(mProgressNotificationId, mBuilder.build())
Toast.makeText(this, " Updated progress to $progressCurrent%", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, " Please send a progress bar notice first ", Toast.LENGTH_SHORT).show()
}
}
The update progress is also through setProgress
, Modify the current progress value .
There are two types of updates :
- Update progress : Modify the progress value
- Download complete : Both the total progress and the current progress are set to 0 that will do , Also update the copy
Be careful : If there are multiple progress notifications , How to update to the specified notification , It's through NotificationId
Matching .
Author:yechaoa
4.5、 Large text notification
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([email protected], mBigTextChannelId)
.setContentTitle(" Large text notification ")
.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())
}
- setStyle(NotificationCompat.BigTextStyle().bigText(bigText))
By default, a maximum of one line is displayed for the notification content , Excess will be cropped , And cannot be expanded , The experience of content disclosure is very bad , The displayed content may not attract users to click to view , So there is also a large text notification ,
Once and for all, no matter how many lines of content , Are notified in large text , The specific display allows the system to adapt itself .
4.6、 Large picture notification
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([email protected], mBigImageChannelId)
.setContentTitle(" Large picture notification ")
.setContentText(" There are beauties , Expand and see ")
.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())
}
Similar to large text notification
- setStyle(NotificationCompat.BigPictureStyle().bigPicture(bigPic))
There is a point of attention , When there are multiple notifications , The default is merged , It is not unfolded , So you can go through setContentText(" There are beauties , Expand and see ")
Add a hint .
- Currently applied notifications do not exceed
3
strip , It will unfold - exceed
3
strip , Notifications aggregate and collapse
4.7、 Custom notifications
private fun createNotificationForCustom() {
// adapter 8.0 And above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(mCustomChannelId, mCustomChannelName, NotificationManager.IMPORTANCE_DEFAULT)
mManager.createNotificationChannel(channel)
}
// adapter 12.0 And above
mFlag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.FLAG_IMMUTABLE
} else {
PendingIntent.FLAG_UPDATE_CURRENT
}
// Add custom notifications view
val views = RemoteViews(packageName, R.layout.layout_notification)
// Add pause resume event
val intentStop = Intent(mStopAction)
val pendingIntentStop = PendingIntent.getBroadcast([email protected], 0, intentStop, mFlag)
views.setOnClickPendingIntent(R.id.btn_stop, pendingIntentStop)
// Add completion event
val intentDone = Intent(mDoneAction)
val pendingIntentDone = PendingIntent.getBroadcast([email protected], 0, intentDone, mFlag)
views.setOnClickPendingIntent(R.id.btn_done, pendingIntentDone)
// establish Builder
mBuilder = NotificationCompat.Builder([email protected], mCustomChannelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_avatar))
.setAutoCancel(true)
.setCustomContentView(views)
.setCustomBigContentView(views)// Set custom notifications view
// Initiation notice
mManager.notify(mCustomNotificationId, mBuilder.build())
}
If it is a front desk notification of a player , The default layout display does not meet the requirements , Then you will use the custom layout .
adopt RemoteViews
Building custom layouts view. because RemoteViews It's not a real view, It's just a view Description of , Therefore, the event processing still needs the help of PendingIntent
.
- setCustomContentView The default layout displays , That is, the layout in the folded state
- setCustomBigContentView Layout in expanded state
In folded state , It may show some basic information , Take the player for example , For example, the name of the current song 、 singer 、 Pause 、 continue 、 Next, wait , It's almost impossible to show . In the expanded state , Can provide more information , Such as album information , Singer information, etc
The default layout height in these two states :
- Collapse view layout ,
48dp
- Expand view layout ,
252dp
4.8、 Update custom notifications
private fun updateNotificationForCustom() {
// Sending notice Update status and 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)
// Update based on status UI
if (mIsStop) {
views.setTextViewText(R.id.tv_status, " Those dreams that you are very adventurous - Stop playing ")
views.setTextViewText(R.id.btn_stop, " continue ")
mBinding.mbUpdateCustom.text = " continue "
} else {
views.setTextViewText(R.id.tv_status, " Those dreams that you are very adventurous - Playing ")
views.setTextViewText(R.id.btn_stop, " Pause ")
mBinding.mbUpdateCustom.text = " Pause "
}
mBuilder.setCustomContentView(views).setCustomBigContentView(views)
// Reissue notification updates UI, Be careful : It must be the same notice id, namely mCustomNotificationId
mManager.notify(mCustomNotificationId, mBuilder.build())
}
above-mentioned , because RemoteViews Not directly view, So you can go through radio broadcast
The way , Reset the build configuration of this notification , To achieve the effect of updating .
In ancient times v4 There is also... In the bag MediaStyle,AndroidX It has fallen .
5、 Commonly used API
API | describe |
---|---|
setContentTitle | title |
setContentText | Content |
setSubText | Subtitle |
setLargeIcon | Large icon |
setSmallIcon | Small icons |
setContentIntent | Intention when clicking |
setDeleteIntent | Intention when deleting |
setFullScreenIntent | Full screen notification click intention , Incoming call 、 Ring the bell |
setAutoCancel | Click auto cancel |
setCategory | Notification category , apply “ Don't disturb mode ” |
setVisibility | Screen visibility , apply “ Lock screen status ” |
setNumber | Number of notification items |
setWhen | Notice time |
setShowWhen | Whether to display the notification time |
setSound | Prompt tone |
setVibrate | shock |
setLights | Breathing lights |
setPriority | priority ,7.0 |
setTimeoutAfter | Time to cancel ,8.0 And later |
setProgress | speed of progress |
setStyle | Notification style ,BigPictureStyle、BigTextStyle、MessagingStyle、InboxStyle、DecoratedCustomViewStyle |
addAction | Actions on notifications ,10.0 |
setGroup | grouping |
setColor | The background color |
6、 Each version fits
since Android 4.0 Support notification , Almost every version has various changes , It is also hard to develop ...
6.1、Android 5.0
6.1.1、 Important notice
Android 5.0 Start , Support important notifications , Also known as header notice .
6.1.2、 Lock screen notice
Android 5.0 Start , Support lock screen notification , It is displayed on the lock screen desktop when the screen is locked .
from 8.0 Start , Users can enable or disable lock screen notification through notification channel settings ...
6.1.3、 Don't disturb mode
5.0 Start , All sounds and vibrations will be organized in do not disturb mode ,8.0 In the future, it can be set according to the channel .
6.2、Android 7.0
6.2.1、 Set notification priority
7.1 And the following :
mBuilder = NotificationCompat.Builder([email protected], mNormalChannelId)
...
.setPriority(NotificationCompat.PRIORITY_DEFAULT) // 7.0 set priority
8.0 And above are changed into channels .
6.2.2、 Reply operation
7.0 Introduce the function of direct reply operation
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()
}
6.2.3、 Notice of news
7.0 Start to support message type notifications 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()
from 8.0 Start , The message type is displayed as a folding type ...
6.2.4、 Notification grouping
7.0 Start , Notification supports grouping , Where more than one notice applies .
6.3、Android 8.0
6.3.1、 Create notification channels
Create notification channels , And importance
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(mHighChannelId, mHighChannelName, NotificationManager.IMPORTANCE_HIGH)
mManager.createNotificationChannel(channel)
}
Delete channel
notificationManager.deleteNotificationChannel(id)
6.3.2、 Notice corner
8.0 Start , Support to set whether the corner mark on the desktop is displayed during notification
val mChannel = NotificationChannel(id, name, importance).apply {
description = descriptionText
setShowBadge(false)
}
6.3.3、 Notification restrictions
8.1 Start , Notification sounds cannot be emitted more than once per second .
6.3.4、 The background color
8.0 Start , Set the background color of the notification .
6.4、Android 10.0
6.4.1、 Add operation
mBuilder = NotificationCompat.Builder([email protected], mHighChannelId)
...
.addAction(R.mipmap.ic_avatar, " Go to see ", pendingIntent)// Actions on notifications
6.4.2、 Full screen intention
10.0 Full screen intent needs to be in manifest Apply for USE_FULL_SCREEN_INTENT
jurisdiction
6.5、Android 12.0
6.5.1、 Unlock device
12.0 And above , You can set that you need to unlock the device to operate :setAuthenticationRequired
val moreSecureNotification = Notification.Builder(context, NotificationListenerVerifierActivity.TAG)
.addAction(...)
// from a lock screen.
.setAuthenticationRequired(true)
.build()
6.5.2、 Custom notifications
from 12.0 Start , Fully customized notifications will not be supported , Would provide Notification.DecoratedCustomViewStyle
replace ...
6.5.3、PendingIntent
12.0 It needs to be clearly set up flag, Otherwise, there will be an error :
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([email protected], 0, intentStop, mFlag)
views.setOnClickPendingIntent(R.id.btn_stop, pendingIntentStop)
After carding and adapting , I really feel that Androider bitter
7、Github
The code also has detailed comments , welcome star
8、 Reference documents
- Notifications Overview
- NotificationManager
- Notification.Builder
- Notification
- NotificationChannel
- Create a Custom Notification Layout
author :yechaoa
link :https://juejin.cn/post/7113509911887085581
source : Rare earth digs gold
The copyright belongs to the author . Commercial reprint please contact the author for authorization , Non-commercial reprint please indicate the source .
边栏推荐
- Three. Introduction to JS learning notes 17: mouse control of 3D model rotation of JSON file
- Numpy -- epidemic data analysis case
- Mesh merging under ue4/ue5 runtime
- Numpy -- data cleaning
- When opening the system window under UE4 shipping, the problem of crash is attached with the plug-in download address
- 15. Using the text editing tool VIM
- Mysql database backup script
- Cocos creator collision and collision callback do not take effect
- Monthly observation of internet medical field in May 2022
- Webcodecs parameter settings -avc1.42e01e meaning
猜你喜欢
How does geojson data merge the boundaries of regions?
星瑞格数据库入围“2021年度福建省信息技术应用创新典型解决方案”
Getting started with webgl (1)
Numpy --- basic learning notes
Steps to create P8 certificate and warehousing account
深度之眼(六)——矩阵的逆(附:logistic模型一些想法)
无线传感器网络--ZigBee和6LoWPAN
Dotween -- ease function
融云斩获 2022 中国信创数字化办公门户卓越产品奖!
Webgl texture
随机推荐
How to deploy the super signature distribution platform system?
Postman generate timestamp, future timestamp
What is Base64?
Numpy --- basic learning notes
AB package details in unity (super detail, features, packaging, loading, manager)
Three. JS introductory learning notes 08:orbitcontrols JS plug-in - mouse control model rotation, zoom in, zoom out, translation, etc
The rebound problem of using Scrollview in cocos Creator
Points for attention in porting gd32 F4 series programs to gd32 F3 series
SPI master RX time out interrupt
有钱人买房就是不一样
15. Using the text editing tool VIM
保证接口数据安全的10种方案
尤雨溪,来了!
Webgl texture
How to build your own super signature system (yunxiaoduo)?
Cocos uses custom material to display problems
Three. JS introductory learning notes 0: illustration of how webgl and threejs work
C4D learning notes 2- animation - timeline and time function
leetcode 241. Different ways to add parentheses design priority for operational expressions (medium)
航運船公司人工智能AI產品成熟化標准化規模應用,全球港航人工智能/集裝箱人工智能領軍者CIMC中集飛瞳,打造國際航運智能化標杆