欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2024-03-07 11:29:21
写android通知的时候发现notification的setlatesteventinfo被弃用,于是搜素并整理了一下新的android通知的基本用法。 一、获取not...

写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 通知栏的知识资料整理,后续继续补充,谢谢大家对本站的支持。