Android中的消息通知(NotificationManager和Notification)

来源:互联网 发布:七天网络成绩查询网页 编辑:程序博客网 时间:2024/05/02 00:15

在Android开发过程中可能会遇到一些需要消息通知提醒之类的功能,提到了消息提醒就不得不提到NotificationManager和Notification了。

 

发送通知挺简单的,也就是new一个Notification的对象,设置一些必要的参数,最后交给NotificationManager把消息发出去就OK了。

1.得到一个NotificationManager:

Java代码  收藏代码
  1. NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  

2.new一个Notification并设置一些参数:

Java代码  收藏代码
  1. Notification notification = new Notification();  
  2. notification.icon = R.drawable.icon; // 通知图标  
  3. // notification.defaults = Notification.DEFAULT_SOUND;// 设置默认铃声  
  4. // notification.defaults = Notification.DEFAULT_VIBRATE;// 设置默认震动  
  5. notification.defaults = Notification.DEFAULT_ALL; // 设置铃声震动  
  6. notification.tickerText = "消息通知"// 显示的内容  
  7. notification.flags |= Notification.FLAG_AUTO_CANCEL; // 当你单击是它会消失  
  8. Context context = getApplicationContext();  
  9. CharSequence contentTitle = "您有新的消息";  
  10. CharSequence contentText = "来自闹台套";  
  11. notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);  

 3.发送通知:

Java代码  收藏代码
  1. notificationManager.notify(0, notification); // 第一个参数如果相同的话指的是同一个notification,只显示一个通知  

 4.消息通知的更新:

    这个只需再次调用setLatestEventInfo()方法再次发送通知就行了。



我在这里只是写了些常用的简单的,如果用到更加复杂的还是看看Google的文档去吧,也欢迎大家补充!