Android里Notification介绍


今天介绍下Android里面的Notification。

在hello world基础修改就可以了。里面加一个button。给button添加监听事件,监听事件完成Notification。

代码如下

  1. NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);   
  2.                
  3.                
  4.                 Notification notif = new Notification();   
  5.         //notif.tickerText="位置已经刷新";   
  6.               notif.vibrate = new long[] { 100250100500};   
  7.              nm.notify(0, notif);  

这就完成了一个极为简单的,单击触发震动的Notification。

如果想要有文字之类的怎么办呢?Nofication的初始化就要变了,Notification有3种初始化方式,看api。我就不多说。

  1. Notification notif = new Notification(R.drawable.map_icon,"位置已经刷新",   
  2.                 System.currentTimeMillis());  

这样就行了吗?不行,运行会出异常。再加上

  1.  PendingIntent contentIntent = PendingIntent.getActivity(getBaseContext(), 0,   
  2.                       new Intent(map.this,IncomingMessageView.class), 0);   
  3. //这是Notification的点击事件,就是点击了Notification之后触发的事件。new Intent就是点击Notification之后跳转到下一个activity    
  4.  notif.setLatestEventInfo(getBaseContext(), "这是title""这是消息内容哦!", contentIntent);  
 

具体的参数可以参考开发文档。如果我想点击Notification清除Notification怎么弄?  

  1. NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);   
  2.       // cancel the notification that we started in IncomingMessage   
  3.       nm.cancelAll();   
  4.       this.finish();  

想运行什么都可以在new Intent后面的那个类里面写,另外Notification的很多参数都可以写,比如播放声音啊,之类的。

相关内容