关于Android 自定义通知栏UI(RemoteViews)的使用(一):Notification的基本使用

676 阅读2分钟

「这是我参与2022首次更文挑战的第1天,活动详情查看:2022首次更文挑战

前言

为什么要写这样的一篇文章呢,说下背景吧,其实在这之前没有用过RemoteViews或者说接触过,没有太深入了解,一般使用通知栏,用系统自带的Notification就基本满足需求,因为对通知栏的UI展示需求没有太刚性,基本对通知需求不是特别要求都不会care这个UI,满足功能就可以了,当然也会有简单的自定义,像修改通知栏的图标啊,这些还是比较基础的,废话不多说,先看下基本的Notification的用法吧

通知使用

基本使用步骤:
1、首先创建一个NotificationManager来进行管理
NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

2、通过构造者模式构建一个Notification对象,由于安卓系统的不断升级,对于不同版本的系统会有一定的兼容性问题, 所以这里使用NotificationCompat类来兼容各个版本。

Notification notification = new NotificationCompat.Builder(MainActivity.this).build();

3、设置基本的属性设置

.setContentText("这是测试通知内容") //设置内容
.setWhen(System.currentTimeMillis())  //设置时间
.setSmallIcon(R.mipmap.ic_launcher)  //设置小图标
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))   //设置大图标

4、通过调用notify()来显示通知(第一个参数是ID, 保证每个通知所指定的id都是不同的,第二个参数是notification对象)

manager.notify(1,notification);

5、其他的功能设置
1)跳转功能: 使用PendingIntent进行通知点击跳转功能。
PendingIntent的用法:
1.通过getActivity()、getBroadcast()、getService()方法获取实例
2.参数(Context context, int requestCode, Intent intent, int flags)
第一个参数:Context
第二个参数:requestCode 一般用不到 ,通常设置为0
第三个参数:intent
第四个参数:flags 用于确定PendingIntent的行为。这里传0就行
3.使用

Intent intent = new Intent(MainActivity.this,NotificationActivity.class);
                PendingIntent pi = PendingIntent.getActivity(MainActivity.this,0,intent,0);
                NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                Notification notification = new NotificationCompat.Builder(MainActivity.this)
                        .setContentTitle("这是测试通知标题")  //设置标题
                        .setContentText("这是测试通知内容") //设置内容
                        .setWhen(System.currentTimeMillis())  //设置时间
                        .setSmallIcon(R.mipmap.ic_launcher)  //设置小图标  只能使用alpha图

2)取消通知
取消通知有2种方式:
1.调用setAutoCancel(true)

Notification notification = new NotificationCompat.Builder(MainActivity.this)
                        ...
                       .setAutoCancel(true) //设置为自动取消
                        .build();
                manager.notify(1,notification);

2.在跳转后的Activity中

NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.cancel(1);

cancle里面的参数是发送通知时传的通知Id

以上就是通知的简单使用,下面会对通知的高阶使用做讲解,有问题的掘友可以留言提问