一、创建一个普通Notification
- 创建通知构造者
NotificationCompat.Builder builder=new NotificationCompat.Builder(MainActivity.this);
- 设置通知的图标、标题和内容文本
builder.setSmallIcon(R.mipmap.ic_laucher)
.setContentTitle("亲,福利到啦!")
.setContentText("点击访问购物页面");
- 设置表示通知访问的目标组件的意图
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
- 创建启动Activity的PendingIntent
PendingIntent pi=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
- 设置通知的意图
builder.setContentIntent(pi);
- 创建通知管理器
NotificationManager manager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
- 创建Notifiaction实例
Notification notification=builder.build();
- 设置通知的标志,点击通知后,通知自动清除
notification.flags=Notification.FLAG_AUTO_CANCEL;
- 发送通知
manager.notify(99,builder.build());
二、用通知Notification开启Activity
NotificationCompat.Builder builder=new NotificationCompat.Builder(this);
builder.setContentTitle("亲,购物啦")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText("点击我进入购物界面");
Intent intent=new Intent(MainActivity.this,BuyActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
//创建通知对象
Notification notification=builder.build();
notification.flags=Notification.FLAG_AUTO_CANCEL;
//获取系统服务,创建通知管理器
NotificationManager manager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(99,notification);
三、用Notification发送广播
NotificationCompat.Builder builder=new NotificationCompat.Builder(this);
builder.setContentTitle("发送服务")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText("点击我发送服务");
Intent intent=new Intent(MainActivity.this,MyService.class);
PendingIntent pendingIntent=PendingIntent.getService(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
//创建通知对象
Notification notification=builder.build();
notification.flags=Notification.FLAG_AUTO_CANCEL;
//获取系统服务,创建通知管理器
NotificationManager manager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(90,notification);