notification通知

本文介绍了如何在Android系统中创建并显示通知于状态条和状态栏,包括创建NotificationManager、实例化Notification、设置属性、显示内容及执行通知的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通知创建之后,需要显示在状态条和状态栏中。所谓状态条,就是手机最上方的长方形区域,一般用于显示电量、信号、时间等。而状态栏,就是将状态条下来之后出现的View。一般用于显示通知内容、正在运行的程序、系统设置的一些快捷方式等。

创建一个通知,需要显示在状态条,和状态栏中。




具体步骤为:

1、创建一个 NotificationManager:

[java]  view plain copy
  1. NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  
2、实例化一个 Notification,并且设置其属性:

[java]  view plain copy
  1. Notification notification = new Notification(R.drawable.notification, "通知滚动显示文本", System.currentTimeMillis());  
Notification(int icon, CharSequence tickerText, long when):

第一个参数是设置其小图标;第二个参数是设置文本内容;第三个参数是设置时间。

3、设置 Notification 的 flags,用户在点击通知之后,通知会自动消失;

[java]  view plain copy
  1. notification.flags = notification.FLAG_AUTO_CANCEL;  
4、设置状态栏显示的内容:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. notification.setLatestEventInfo(this"通知标题""通知内容", contentintent);  
setLatestEventInfo(Context, CharSequence, CharSequence, PendingIntent)

第一个参数是上下文,第二个参数是通知的标题,第三个参数是通知的内容,第四个参数是一个 PendingIntent ,也就是延期意图,用于处理即将发生的意图。

PendingIntent :例如短信通知,当用户点击短信通知之后,系统会跳转到短信的界面。PendingIntent  就是起到这个作用。

PendingIntent  也可以看做是一个 Intent 的包装,其实质还是一个 Intnet 。

代码实现过程中,首先是实例化一个 Intent ,然后设置其 Action 和 Data ,然后将其包装成 PendingIntent 。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. Intent intent = new Intent();  
  2. intent.setAction(Intent.ACTION_CALL);  
  3. intent.setData(Uri.parse("tel:110"));  
  4. // PendingIntent延期意图  
  5. PendingIntent contentintent = PendingIntent.getActivity(this0, intent, 0);  
5、执行通知:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. nm.notify(0, notification);  

完整代码:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public void click1(View view) {  
  2.     NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  
  3.     Notification notification = new Notification(R.drawable.notification, "通知滚动显示文本", System.currentTimeMillis());  
  4.     notification.flags = notification.FLAG_AUTO_CANCEL;  
  5.       
  6.     Intent intent = new Intent();  
  7.     intent.setAction(Intent.ACTION_CALL);  
  8.     intent.setData(Uri.parse("tel:110"));  
  9.     // PendingIntent延期意图  
  10.     PendingIntent contentintent = PendingIntent.getActivity(this0, intent, 0);  
  11.     notification.setLatestEventInfo(this"通知标题""通知内容", contentintent);  
  12.       
  13.     nm.notify(0, notification);  
  14. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值