Notification的使用(一)

一、Notification的基本使用

通知的创建可以放在Activity、Service、BroatcastReceiver里面。

1.创建通知

1.1NotificationManager

首先需要创建一个NotificationManager对象用来管理通知。创建方式Context.getSystemService()方法,参数传入Context.NOTIFICATION_SERVICE。

NotificationManagermanager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

1.2Notification

1.2.1由于Android每个版本都会对通知进行部分修改,所以为了统一,我们使用v4包里面的NotificationCompat类,这是一个空的通知:

Notification notification =new  NotificationCompat.Builder(context).build();

1.2.2最基本设置的natification:

Notificationnotification=newNotificationCompat.Builder(mContext)

                        .setContentTitle("这是通知标题")  //通知标题

                        .setContentText("这是通知内容")//通知内容

                        .setWhen(System.currentTimeMillis())//通知时间,毫秒数

                        .setAutoCancel(true)//点击后自动取消

                        .setSmallIcon(R.mipmap.ic_launcher)//通知的小图标(状态栏上显示,只能使用纯alpha通道的图片)

                        setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))///通知的大图片,通知栏上显示

                        .build();//通知创建


Notification的使用(一)
通知大图标
Notification的使用(一)
通知小图标


1.3发出通知

利用NotificationManager的notify方法发出通知,两个参数,第一个是通知的id,该条通知的唯一标识,可以用来取消通知等等。第二个参数是Notification对象,代码如下:

manager.notify(1,notification);

2.通知的点击事件

2.1 获取PendingIntent对象

要实现的通知的点击效果需要使用PendingIntent类,调用静态方法可以获得对象。

PendingIntent  pendingIntent=PendingIntent.getActivity(mContext,0,intent,PendingIntent.FLAG_ONE_SHOT);//跳转activity

PendingIntent pendingIntent=PendingIntent.getService(mContext,0,intent3,PendingIntent.FLAG_ONE_SHOT);跳转服务

PendingIntent  pendingIntent=PendingIntent.getBroadcast(mContext,0,intent3,PendingIntent.FLAG_ONE_SHOT);//跳转广播


PendingIntent pendingIntent=PendingIntent.getForegroundService(mContext,0,intent3,PendingIntent.FLAG_ONE_SHOT);//跳转前台服务(要求API 26)

由上面可以看出虽然方法不一样,但是方法的参数都是一样的,第一个参数是上下文Context,第二个参数是请求码,随便填一个int值,第三个参数是要执行的”意图“Intent,第四个参数是确定PendingIntent的行为,有4个可选值,PendingIntent.FLAG_ONE_SHOT、PendingIntent.FLAG_NO_CREATE、PendingIntent.FLAG_CANCEL_CURRENT、PendingIntent.FLAG_UPDATE_CURRENT具体含义可以查看相关文档,或者从字面理解。

2.2设置到Notification里面

通过在创建Notification对象的时候添加setContentIntent(),传入PendingIntent对象


Notificationnotification2=newNotificationCompat.Builder(mContext)

        .setContentTitle("这是通知标题")//通知标题

         .setContentText("这是通知内容")//通知内容

         .setContentIntent(serviceIntent)//点击后的操作

         .setWhen(System.currentTimeMillis())//通知时间,毫秒数

         .setAutoCancel(true)//点击后自动取消

         .setSmallIcon(R.mipmap.ic_launcher)//通知的小图标(状态栏上显示,只能使用纯alpha通道的图片)

         .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))///通知的大图片,通知栏上显示

        .build();//通知创建

其他步骤照旧就OK了。

传送门:notification的使用(二):http://blog.csdn.net/houjianbo188/article/details/78021756