Notification代表一种全局效果的通知,程序通过NotificationManager服务来发送。
使用Notification步骤:
(1)调用getSystemService(NOTIFICATION_SERVICE)方法获取系统的notificationManager服务;
(2)通过构造器创建一个Notification对象;
(3)为Notification设置各种属性;
(4)通过NotificationManager发送Notification。
例子:
public class MainActivity extends Activity {
Button btTest ;
int i = 0 ;
static final int NOTIFICATION_ID = 0x1123 ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btTest = (Button) findViewById(R.id.btTest) ;
btTest.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(i%2==0){
Intent intent = new Intent(MainActivity.this,MainActivity.class) ;
PendingIntent pi = PendingIntent.getActivity(MainActivity.this,0,intent,0) ;
Notification notify = new Notification() ;
notify.icon = R.drawable.ic_launcher ;
notify.tickerText = "通知" ;
notify.when = System.currentTimeMillis() ;
notify.defaults = Notification.DEFAULT_SOUND ;
notify.defaults = Notification.DEFAULT_LIGHTS ;
notify.setLatestEventInfo(MainActivity.this, "普通通知", "点击查看", pi) ;
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE) ;
notificationManager.notify(NOTIFICATION_ID, notify);
}
else{
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE) ;
notificationManager.cancel(NOTIFICATION_ID) ;
}
i++ ;
}
}) ;
}