Notification通知创建

Notification通知创建

由于通知是一个远程视图,所以创建通知在状态栏显示需要用到三个主要的对象:

一、PendingIntent对象,用来承载Intent对象的,Intent对象主要是定义通知的意图去向

二、Notification对象,该对象需要借助NotificationCompat 子类Build的对象通过build()方法获得。

三、NotificationManger服务对象,该对象的主要作用是将notification对象发送通过notify()方法

 

 

创建系统通知样式
第一步:创建一个点击该通知栏启动其他Activity的Intent(意图)对象,该activity需要注册action
Intent intent = new Intent(acton);
PendingIntent pi1 = PendingIntent.getActivity(this, 0, intent, 0); 
第二步:创建通知对象notificaton,而notificaton对象需要Builder对象来建立,所以创建Builder对象,并利用该对象设置通知的各种信息
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setAutoCancel(true);// 打开该通知,通知自动消失
builder.setTicker("有新的消息,注意查收!!");// 设置显示在状态栏的通知提示信息
Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.notification);
builder.setLargeIcon(bitmap);// 设置通知栏中的通知下拉后显示的图标,图片格式为bitmap型
builder.setSmallIcon(R.drawable.icon);// 设置通知图标
builder.setContentTitle("样式通知");// 设置通知内容的标题
builder.setContentText("恭喜您,您被录取了,请于下周一前来报道!!");// 设置通知的内容
builder.setContentIntent(pi1);// 设置点击通知将要启动的Inent
// 利用builder对象建立通知对象notificaton,通过build()方法
android.app.Notification notification = builder.build(); 
// 第三步:利用系统的NotificationManager服务发送通知,通过getSystemService()获取系统的NotificationManager服务
 NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
nm.notify(NOTIFICATION_ID, notification);

 

 
创建自定义样式:
// 创建通知意图
Intent intent2 = new Intent("com.example.notification.OtherActivity");
PendingIntent pi2 = PendingIntent.getActivity(this, 0, intent2, 0);
// 创建通知对象notification,该对象那需要build对象来简介建立
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.notice);
builder.setAutoCancel(true);// 打开该通知,通知自动消失
builder.setTicker("有新的消息,注意查收!!");// 设置显示在状态栏的通知提示信息
// 加载自定义通知布局样式,也就是这里不用在通过builder对象来设置通知信息,xml文件已经定义好!!
// 由于通知是一个远程视图,所以必须通过RemoteViews对象获取xml文件并形成通知视图
RemoteViews remoteViews = new RemoteViews(this.getApplication().getPackageName(), R.layout.notification);
// 然后将远程视图利用setContent()设置到通知中去显示
builder.setContent(remoteViews);
builder.setContentIntent(pi2);// 设置点击通知将要启动的Inent
// 利用builder对象建立通知对象notificaton,通过build()方法
android.app.Notification notification = builder.build();
// 通过getSystemService()获取系统的NotificationManager服务,在发送通知
NotificationManager nm  = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(MY_NOTIFICATION_ID, notification);
posted on 2013-10-26 15:45  知行立远  阅读(401)  评论(0编辑  收藏  举报