Android-通知栏Notification学习

https://blog.csdn.net/vipzjyno1/article/details/25248021

一、使用步骤

1)创建一个通知栏的Builder构造类 (Create a Notification Builder)

2)定义通知栏的Action (Define the Notification’s Action)

定义通知栏的Action (Define the Notification’s Action)

3)设置通知栏点击事件 (Set the Notification’s Click Behavior)

设置通知栏点击事件 (Set the Notification’s Click Behavior)

4)通知 (Issue the Notification)

二、代码实现

1)获取状态通知栏管理

NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

2)实例化通知栏构造器

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);

3)对builder设置

mBuilder.setContentTitle("测试标题")//设置通知栏标题
	.setContentText("测试内容") //设置通知栏显示内容
	.setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL)) //设置通知栏点击意图
//	.setNumber(number) //设置通知集合的数量
	.setTicker("测试通知来啦") //通知首次出现在通知栏,带上升动画效果的
	.setWhen(System.currentTimeMillis())//通知产生的时间,会在通知信息里显示,一般是系统获取到的时间
	.setPriority(Notification.PRIORITY_DEFAULT) //设置该通知优先级
//	.setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消  
	.setOngoing(false)//ture,设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
	.setDefaults(Notification.DEFAULT_VIBRATE)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置,使用defaults属性,可以组合
	//Notification.DEFAULT_ALL  Notification.DEFAULT_SOUND 添加声音 // requires VIBRATE permission
	.setSmallIcon(R.drawable.ic_launcher);//设置通知小ICON

4)设置通知栏PendingIntent(点击动作事件等)

  • 属性
FLAG_ONE_SHOT   表示返回的PendingIntent仅能执行一次,执行完后自动取消

FLAG_NO_CREATE     表示如果描述的PendingIntent不存在,并不创建相应的PendingIntent,而是返回NULL

FLAG_CANCEL_CURRENT      表示相应的PendingIntent已经存在,则取消前者,然后创建新的PendingIntent,这个有利于数据保持为最新的,可以用于即时通信的通信场景

FLAG_UPDATE_CURRENT     表示更新的PendingIntent
  • 在各种情况下情况下它还会根据各种情况出发效果:

    contentIntent:在通知窗口区域,Notification被单击时的响应事件由该intent触发;

    deleteIntent:当用户点击全部清除按钮时,响应该清除事件的Intent;

    fullScreenIntent:响应紧急状态的全屏事件(例如来电事件),也就是说通知来的时候,跳过在通知区域点击通知这一步,直接执行fullScreenIntent代表的事件。

Intent intent = new Intent(context,XXX.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
mBuilder.setContentIntent(pendingIntent)

5)发通知

mNotificationManager.notify(notifyId, mBuilder.build());

三、自定义通知栏

https://juejin.im/entry/578ef709c4c971005e0b3251

这里要用到RemoteViews这个类。注意RemoteViews类,在自定义视图布局文件中,仅支持FrameLayout、LinearLayout、RelativeLayout三种布局控件和AnalogClock、Chronometer、Button、ImageButton、ImageView、ProgressBar、TextView、ViewFlipper、ListView、GridView、StackView和AdapterViewFlipper这些显示控件,不支持这些类的子类或Android提供的其他控件。否则会引起ClassNotFoundException异常

步骤如下:

1)创建自定义视图

2)获取远程视图对象(注:Notification的contentView不能为空)

3)设置PendingIntent(来响应各种事件)

4)发起Notification

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章