PendingIntent、Notification常用方法

PendingIntent

PendingIntent它的直译是:待处理意图,这样翻译,大家就猜出它的作用是什么了,用于处理一些定义但是不立即使用的意图,最常见的就是用户点击通知,然后跳转指定的页面:

最常用的方法估计就下面这个了:

public static PendingIntent getActivity (Context context, int requestCode, Intent intent, int flags)

类似的还有:

  • PendingIntent.getActivity(context, 0, notifyIntent, 0);
  • PendingIntent.getService(context, 0, notifyIntent, 0);
  • PendingIntent.getBroadcast(context, 0, notifyIntent, 0);

第一个参数是上下文,第二个参数 requestCode,第三个参数是 Intent,第四个参数是对参数的操作标识

第一、三个没什么好说的,重点介绍另外两个:

第二个参数:requestCode:

Private request code for the sender
当同时有多个通知的时候,可通过这个参数来互相区别

第四个参数:flags

FLAG_CANCEL_CURRENT:
Flag indicating that if the described PendingIntent already exists, the current one should be canceled before generating a new one.
如果当前系统中已经存在一个相同的PendingIntent对象,那么就将先将已有的PendingIntent取消,然后重新生成一个PendingIntent对象。

FLAG_UPDATE_CURRENT:
Flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent.
如果系统中有一个和你描述的PendingIntent对等的PendingInent,那么系统将使用该PendingIntent对象,但是会使用新的Intent来更新之前PendingIntent中的Intent对象数据,例如更新Intent中的Extras。

FLAG_NO_CREATE:
Flag indicating that if the described PendingIntent does not already exist, then simply return null instead of creating it.
如果当前系统中不存在相同的PendingIntent对象,系统将不会创建该PendingIntent对象而是直接返回null。

FLAG_ONE_SHOT:
Flag indicating that this PendingIntent can be used only once.
该PendingIntent只作用一次。在该PendingIntent对象通过send()方法触发过后,PendingIntent将自动调用cancel()进行销毁,那么如果你再调用send()方法的话,系统将会返回一个SendIntentException。

FLAG_CANCEL_CURRENT和FLAG_UPDATE_CURRENT的区别在于能否新new一个Intent,FLAG_CANCEL_CURRENT能够新new一个Intent,而FLAG_UPDATE_CURRENT则不能。

Notification

显示一则通知,旧的Notification有不少方法是已经过时的,下面是新的:

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

posted on 2016-11-16 10:59  疯狂的妞妞  阅读(434)  评论(0编辑  收藏  举报

导航