Notification通知启动三大组件

作者: dayang | 来源:发表于2017-03-30 15:08 被阅读59次

一、创建一个普通Notification

  1. 创建通知构造者
NotificationCompat.Builder builder=new NotificationCompat.Builder(MainActivity.this);
  1. 设置通知的图标、标题和内容文本
builder.setSmallIcon(R.mipmap.ic_laucher)
.setContentTitle("亲,福利到啦!")
.setContentText("点击访问购物页面");
  1. 设置表示通知访问的目标组件的意图
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
  1. 创建启动Activity的PendingIntent
PendingIntent pi=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
  1. 设置通知的意图
builder.setContentIntent(pi);
  1. 创建通知管理器
NotificationManager manager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
  1. 创建Notifiaction实例
Notification notification=builder.build();
  1. 设置通知的标志,点击通知后,通知自动清除
notification.flags=Notification.FLAG_AUTO_CANCEL;
  1. 发送通知
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);

相关文章

网友评论

    本文标题:Notification通知启动三大组件

    本文链接:https://www.haomeiwen.com/subject/szqhvttx.html