当前位置:网站首页>Details of notification (status bar notification)
Details of notification (status bar notification)
2022-07-25 22:59:00 【Sharp surge】
Introduction to this section :
This section brings Android Control used to display notification information in the status bar :Notification, Believe most learn Android All know him very well , And there's a lot about Notification The tutorials are based on 2.x Of , and It is now common Android The equipment is basically 4.x above , Even 5.0 All of the above ; Their own Notification It's all different ! This section is based on 4.x The above Notification, and 5.0 The above Notification We will do the advanced tutorial Android 5.0 The new features are explained in the chapter ~
The official document is right Notification Some introductions of :
design idea :Notifications in Android 4.4 and Lower
translation : notice
API file :Notification
Visit the above website , You may need a ladder ~
1. Interpretation of design documents
1)Notification Basic layout

The constituent elements above are :
- Icon/Photo: Large icon
- Title/Name: title
- Message: Content information
- Timestamp: Notice time , The default is the time when the system sends a notification , It can also be done through setWhen() To set up
- Secondary Icon: Small icons
- Content text , A text on the left-hand side of the small icon
2) Expand the layout
stay Jelly Bean You can provide more details of the event for the notification . You can expand the layout to show the first few lines of the message or the preview of the image . In this way, users can see more content - Sometimes you can even see the whole news . The user can go through pinch-zoom Or slide your fingers to open the extended layout .Android Two extended layouts are provided for a single message ( Words and images ) For you to use when developing applications .

About other design things , I won't mention them one by one , If you are interested, please check the above API file , I know This Notification stay 4.x The above versions can be varied ! We pay more attention to How to write code to use this thing , Now let's learn Notification Usage of !
2.Notification The basic use process of
The status notification bar mainly involves 2 Classes :Notification and NotificationManager
Notification: Notification information class , It corresponds to the properties of the notification bar
NotificationManager: It is the management class of status bar notification , Be responsible for sending notice 、 Clear notifications and other operations .
The basic process used :
- Step 1. get NotificationManager object : NotificationManager mNManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
- Step 2. Create a notification bar Builder Construction class : Notification.Builder mBuilder = new Notification.Builder(this);
- Step 3. Yes Builder Make relevant settings , Such as the title , Content , Icon , Action, etc !
- Step 4. call Builder Of build() Method is notification assignment
- Step 5. call NotificationManager Of notify() Method send notification !
- PS: In addition, we can call NotificationManager Of cancel() Method cancel notification
3. Some methods related to setting up :
Notification.Builder mBuilder = new Notification.Builder(this);
Then call the following related methods to set :( official API file :Notification.Builder) The common methods are as follows :
- setContentTitle(CharSequence): Set title
- setContentText(CharSequence): Set contents
- setSubText(CharSequence): Set a small line of text below the content
- setTicker(CharSequence): Set the text message displayed at the top when you receive a notification
- setWhen(long): Set notification time , The general setting is when receiving the notification System.currentTimeMillis()
- setSmallIcon(int): Set the small icon in the lower right corner , This small icon will also be displayed at the top when receiving the notification
- setLargeIcon(Bitmap): Set the large icon on the left
- setAutoCancel(boolean): The user clicks Notification Whether to cancel the notification after clicking the panel ( The default is not to cancel )
- setDefaults(int): Add a voice to the notification 、 The simplest of flashing lights and vibration effects 、 Use the default (defaults) attribute , You can combine multiple attributes ,
Notification.DEFAULT_VIBRATE( Add default vibration reminder );
Notification.DEFAULT_SOUND( Add default sound reminder );
Notification.DEFAULT_LIGHTS( Add default Tri Color Light reminder )
Notification.DEFAULT_ALL( Add default above 3 All kinds of reminders )- setVibrate(long[]): Set the vibration mode , such as :
setVibrate(new long[] {0,300,500,700}); Delay 0ms, Then vibrate 300ms, In delay 500ms, Then vibrate 700ms, About Vibrate The usage will be explained later !- setLights(int argb, int onMs, int offMs): Set tricolor lights , The parameters in turn are : The color of the light , Light duration , Dark time , Not all colors are OK , It's about equipment , Some mobile phones don't have Tri Color Lights yet ; in addition , Also need to Notification Set up flags by Notification.FLAG_SHOW_LIGHTS To support three color light reminder !
setSound(Uri): Set the ringing tone when receiving the notification , You can use the system , You can also set it yourself , Examples are as follows :
.setDefaults(Notification.DEFAULT_SOUND) // Get the default ringtone
.setSound(Uri.parse("file:///sdcard/xx/xx.mp3")) // Get custom ringtones
.setSound(Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "5")) // obtain Android Ringtones in Multimedia LibrarysetOngoing(boolean): Set to ture, Indicates that it is an ongoing notification . They are usually used to express A background task , Users actively participate in ( Such as playing music ) Or waiting in some way , Therefore, the equipment is occupied ( Like a file download , Synchronous operation , Active network connectivity )
- setProgress(int,int,boolean): Set notification with progress bar The parameters are : Maximum value of progress bar , Current progress , Whether the progress is uncertain If it is a determined progress bar : call setProgress(max, progress, false) To set up notifications , When updating the progress, send a notification here progress, And remove the progress bar after the download , By calling setProgress(0, 0, false) As well as . If it is uncertain ( Continuous activity ) The progress bar , This shows that the activity is continuing when the processing progress cannot be accurately known , So call setProgress(0, 0, true) , At the end of the operation , call setProgress(0, 0, false) And update the notification to remove the indicator bar
setContentIntent(PendingIntent):PendingIntent and Intent It's a little different , It can set the number of executions , Mainly used for remote service communication 、 Alarm 、 notice 、 starter 、 In SMS , In general, it is less used . For example, here through Pending start-up Activity:getActivity(Context, int, Intent, int), Of course, you can also start Service perhaps Broadcast PendingIntent Bit identifier of ( Fourth parameter ):
FLAG_ONE_SHOT Means returned PendingIntent Can only be executed once , Automatically cancel after execution
FLAG_NO_CREATE It means if you describe PendingIntent non-existent , Do not create corresponding PendingIntent, It's going back to NULL
FLAG_CANCEL_CURRENT It means corresponding PendingIntent Already exist , Then cancel the former , And create a new one PendingIntent, This helps keep the data up to date , Communication scenarios that can be used for instant messaging
FLAG_UPDATE_CURRENT Means updated PendingIntent
Examples of use :// Click and jump Activity Intent intent = new Intent(context,XXX.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); mBuilder.setContentIntent(pendingIntent)setPriority(int): set priority :
Corresponding attribute :Notification.PRIORITY_HIGH...
priority user MAX Important and urgent notice , Inform the user that this event is time critical or needs to be handled immediately . HIGH High priority is used for important communication content , For example, SMS or chat , These are more interesting to users . DEFAULT The default priority is used for notifications without special priority classification . LOW Low priority can notify users of events that are not very urgent . MIN For background messages ( For example, weather or location information ). The lowest priority notification will only display icons in the status bar , Only when the user pulls down the notification drawer can you see the content .
4. Code example : The most common Notification:
Let's write a simple example to experience Notification Usage of :
Run the renderings :

Key code :
Direct paste here MainActivity.java Code for :
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Context mContext;
private NotificationManager mNManager;
private Notification notify1;
Bitmap LargeBitmap = null;
private static final int NOTIFYID_1 = 1;
private Button btn_show_normal;
private Button btn_close_normal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = MainActivity.this;
// Create large icons Bitmap
LargeBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.iv_lc_icon);
mNManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
bindView();
}
private void bindView() {
btn_show_normal = (Button) findViewById(R.id.btn_show_normal);
btn_close_normal = (Button) findViewById(R.id.btn_close_normal);
btn_show_normal.setOnClickListener(this);
btn_close_normal.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_show_normal:
// Define a PendingIntent Click on Notification Start one after Activity
Intent it = new Intent(mContext, OtherActivity.class);
PendingIntent pit = PendingIntent.getActivity(mContext, 0, it, 0);
// Set pictures , Notification heading , Send time , Prompt method and other attributes
Notification.Builder mBuilder = new Notification.Builder(this);
mBuilder.setContentTitle(" Ye Liangchen ") // title
.setContentText(" I have a hundred ways to make you stay ~") // Content
.setSubText("—— Remember my name is ye Liangchen ") // A short paragraph below the content
.setTicker(" Received the message sent by Ye Liangchen ~") // The text message displayed in the status bar after receiving the message
.setWhen(System.currentTimeMillis()) // Set notification time
.setSmallIcon(R.mipmap.ic_lol_icon) // Set up small icons
.setLargeIcon(LargeBitmap) // Set the big icon
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE) // Set the default tricolor lights and vibrators
.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.biaobiao)) // Set custom prompt tone
.setAutoCancel(true) // Click set to cancel Notification
.setContentIntent(pit); // Set up PendingIntent
notify1 = mBuilder.build();
mNManager.notify(NOTIFYID_1, notify1);
break;
case R.id.btn_close_normal:
// In addition to being able to ID To cancel Notification Outside , You can also call cancelAll(); Close all notifications generated by the app
mNManager.cancel(NOTIFYID_1); // Cancel Notification
break;
}
}
}The notes are very detailed , I won't go into details ~
5. Code sample download :
Summary of this section :
well , This section introduces Notification stay 4.x Basic usage of version , It's very simple, isn't it ~
Of course, you can also customize Notification If you are interested, you can consult relevant materials by yourself , Here is not slow Studied ~ by the way , Part of this section refers to the following blog, Post link , You can also have a look at : Android Notice bar Notification Integration of Study in an all-round way ( One DEMO Let you fully understand it ) It's very detailed ~ That's all for this section , thank you ~
from :2.5.8 Notification( Status bar notification ) Detailed explanation | Novice tutorial
边栏推荐
- CMU AI PhD first year summary
- JSON object
- Severely crack down on illegal we media operators according to law: it is urgent to purify the we media industry
- JS makes elements get or lose focus
- 面试题 17.11. 单词距离 ●●
- We media people must have four material websites, and don't worry about finding materials anymore
- Network Security Learning (11) scanning and blasting
- The difference between "rewrite" and "overload"
- [MySQL rights] UDF rights (with Malaysia)
- BIO、NIO、AIO的区别?
猜你喜欢

How painful is it to write unit tests?

AI首席架构师12-AICA-工业生产过程优化场景下产业落地解析

Mocha test

单模型常识推理首超人类!HFL登顶OpenBookQA挑战赛
![[training day15] boring [tree DP]](/img/78/dc80076bb9fc4cf008c51b00ece431.png)
[training day15] boring [tree DP]

Learning notes of technical art hundred people plan (2) -- vector

CUDA environment construction

内存分页与调优,内核与用户空间

Review of static routing

新媒体运营策略(以小红书为例)帮助你快速掌握爆款创作方法
随机推荐
Ssh server CBC encryption mode vulnerability (cve-2008-5161)
CUDA environment construction
DOM event object
Stack simulation queue
CMU AI PhD first year summary
码蹄集 精准弹幕
Simple setting of drop-down triangle
Experiment 1, experiment 2 and Experiment 3 of assembly language and microcomputer principle: branch program design / loop program design / subroutine design
BIO、NIO、AIO的区别?
2020-09-17
[training day15] paint road [minimum spanning tree]
如何获取广告服务流量变现数据,助力广告效果分析?
Express framework
invalid syntax
Network Security Learning (XII) OSI and TCP
Notification(状态栏通知)详解
Websocket summary
MySQL data type
[opencv] edge detection [API and source code implementation]
QT add mouse event to control