Android 通知的基本用法示例代码

作者:lqh 时间:2022-09-28 03:54:50 

写android通知的时候发现Notification的setLatestEventInfo被弃用,于是搜素并整理了一下新的android通知的基本用法。

一、获取NotificationManager实例

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

二、创建Notification实例

在这里需要根据project的min-sdk来选择实现方法,MIN API Level < 11的可以使用setLatestEventInfo()方法,以下介绍API Level 11 之后的Notification实例获取方法。

1. MIN API Level < 16 构建Notification实例的方法

1) 创建Notification.Builder实例


     Notification.Builder builder = new Notification.Builder(context)
     .setAutoCancel(true) //设置点击通知后自动取消通知
     .setContentTitle("title") //通知标题
     .setContentText("describe") //通知第二行的内容
     .setContentIntent(pendingIntent) //点击通知后,发送指定的PendingIntent
     .setSmallIcon(R.drawable.ic_launcher); //通知图标,必须设置否则通知不显示

2) 调用Notification.Builder的getNotification()方法获得Notification 

                     notification = builder.getNotification();

2. MIN API Level >=16 构建Notification实例的方法


           Notification notification = new Notification.Builder(context)
           .setAutoCancel(true)
           .setContentTitle("title")
           .setContentText("text")
           .setSmallIcon(R.mipmap.ic_launcher)
           .setContentIntent(pendingIntent)
           .build();

三、发送通知

                          notificationManager.notify(1,notification);

标签:Android,通知
0
投稿

猜你喜欢

  • Maven聚合开发实例详解

    2023-07-14 11:18:12
  • jdk线程池的实现

    2023-07-05 18:44:35
  • springboot 使用自定义的aspect的示例代码

    2023-08-06 08:55:14
  • C#窗体实现酒店管理系统

    2023-05-23 18:58:47
  • 引入mybatis-plus报 Invalid bound statement错误问题的解决方法

    2021-06-01 14:28:00
  • SpringBoot+SpringSession+Redis实现session共享及唯一登录示例

    2023-10-07 07:56:17
  • 我用java实现了王者荣耀的皮肤和英雄技能

    2022-01-13 13:44:09
  • C#对象为Null模式(Null Object Pattern)实例教程

    2023-07-27 15:53:28
  • MyBatis的嵌套查询解析

    2023-11-26 16:58:46
  • Avalonia封装实现指定组件允许拖动的工具类

    2023-01-01 19:03:03
  • Java根据ip地址获取归属地实例详解

    2023-11-25 06:24:38
  • C# 多线程中经常访问同一资源可能造成哪些问题

    2022-09-08 05:22:47
  • SSH框架网上商城项目第23战之在线支付功能实现

    2023-04-22 22:49:19
  • Java定时器问题实例解析

    2021-08-21 21:02:53
  • Java执行cmd命令的举例与注意事项

    2023-11-03 10:21:05
  • Java 8新增的方法参数反射实例分析

    2021-11-20 05:55:30
  • android Launcher3设置默认桌面应用

    2022-07-20 20:18:42
  • Android实现弹出登陆框的方案

    2021-09-03 06:52:36
  • Android基于讯飞语音SDK实现语音识别

    2023-09-26 23:39:05
  • java解决动态配置字段需求问题

    2022-08-03 17:38:30
  • asp之家 软件编程 m.aspxhome.com