0%

基于Android8.0的APP消息推送

基于Android8.0的消息推送

观看B站视频, 文字看不懂 就看视频吧

前言:

​ Android8.0 新版本中 对APP的推送通知开始管理 分为了如下几个重要程度

image-20210318201658957

如何发送一个消息?

我们从后向前分析 都需要用到哪些类 API

  1. 我们通过如下的代码进行发送通知与取消通知

    1
    2
    3
    4
    5
    //4.发送通知
    notificationManager.notify(1, notification); //第一个参数为 这个推送的id 自己设置 取消通知时使用,第二个参数是 通知内容

    // 5. 取消通知
    notificationManager.cancel(1);//第一个参数为 这个推送的id 自己设置 取消通知时使用

    所以我们需要实例化 notificationManager, notification

  2. 实例化notificationManager,并不是通过构造函数来实例化一个对象,而是调用getSystemService(NOTIFICATION_SERVICE)

    1
    2
    private NotificationManager notificationManager;//当作成员变量 方便后续使用 
    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  3. 实例化 notification

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    //3.设置通知属性(标题, 内容等) Builder括号中第二个参数一定要与NotificationChannel中注册的一致【第四步中会提NotificationChannel】

    //下两行代码 为点击通知跳转活动做准备
    Intent intent=new Intent(this,MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

    Notification notification = new NotificationCompat.Builder(this, "little")
    .setContentTitle("西大新闻")//设置通知标题
    .setContentText("硕博楼公寓投入使用")//设置通知内容
    .setSmallIcon(R.drawable.icon)//设置通知图标
    //setLargeIcon 参数类型为Bitmap,需要将图片转换为Bitmap类型 通过BitmapFactory.decodeResource
    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.img))
    .setColor(Color.parseColor("#ff0000"))//设置小图标的颜色 需要Int类型的参数 通过Color.parseColor()

    //########################################################################
    //设置点击通知后跳转到活动 需要PendingIntent 类型的参数
    .setContentIntent(pendingIntent)
    //########################################################################

    .setAutoCancel(true)//设置点击后是否消失
    .build();//固定写法
  4. Andorid8.0 新特性

    1
    2
    3
    4
    5
    6
    //2.Android8.0新特性 系统控制通知的关键程度(可选)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel notificationChannel = new NotificationChannel("little", "测试",
    NotificationManager.IMPORTANCE_HIGH);//设置重要性程度
    notificationManager.createNotificationChannel(notificationChannel);
    }
  5. 实验效果图:

    image-20210318203237693
image-20210318203351880