调用步骤:
- 调用getSystemService(NOTIFICATION_SERVICE)方法获取系统的 Notification Manager服务
- 通过构造器创建一个Notification对象
- 为Notification设置各种属性
- 通过NotificationManager发送Notification
Notification常用方法
1 /*设置large icon*/ 2 .setLargeIcon(bitmap) 3 /*设置small icon*/ 4 .setSmallIcon() 5 /*设置title*/ 6 .setContentTitle() 7 /*设置详细文本*/ 8 .setContentText() 9 /*设置发出通知的时间为发出通知时的系统时间*/ 10 .setWhen(System.currentTimeMillis()) 11 /*设置发出通知时在status bar进行提醒*/ 12 .setTicker("设置状态栏提示文本") 13 /*setOngoing(boolean)设为true,notification将无法通过左右滑动的方式清除 * 可用于添加常驻通知,必须调用cancle方法来清除 */ 14 .setOngoing(true) 15 /*设置点击后通知消失*/ 16 .setAutoCancel(true) 17 /*设置通知数量的显示类似于QQ那种,用于同志的合并*/ 18 .setNumber(2) 19 /*点击跳转Activity*/ 20 .setContentIntent();
示例代码
1 imageToast=(Button) findViewById(R.id.imageToast); 2 imageToast.setOnClickListener(new View.OnClickListener() { 3 @Override 4 public void onClick(View v) { 5 count++; 6 NotificationManager manager =(NotificationManager) getSystemService(NOTIFICATION_SERVICE); 7 8 NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this); 9 10 builder.setSmallIcon(R.mipmap.ic_launcher); 11 builder.setContentTitle("你有"+count+"个新消息");//设置状态栏题目 12 builder.setContentText("设置状态栏文本"); 13 builder.setTicker("设置状态栏提示文本"); 14 builder.setNumber(2);//设置消息数目 15 16 Notification notification = builder.build(); 17 manager.notify(NOTIFICATION_ID,notification); 18 } 19 });