Android(安卓)Notification通知栏、点击事件、悬浮通知的简单实现
16lz
2022-04-11
Notification的三要素
1.小图标 .setSmallIcon()
2.标题 .setContentTitle()
3.内容 .setContentText()
这是一个通知栏的 三要素 有了三要素你的通知栏才能显示出来
一些常用的方法
方法 | 效果 |
---|---|
.setSmallIcon() | 小图标 |
.setContentTitle() | 标题 |
.setContentText() | 内容 |
.setDefaults(Notification.DEFAULT_ALL); | 提醒方式(ALL代表 声音 振动 提示灯兼备) |
.setLargeIcon() | 大图标 |
.setContentIntent() | 点击跳转 |
.setWhen() | 通知时间(何时通知) |
.setAutoCancel(boolean) | 点击后是否关闭通知 |
.setPriority(Notification.PRIORITY_MAX) | 通知的优先级(MAX表示最高级) |
API15以及以下的使用需要注意
1 .java代码中最后那条 .build()方法需要换成.getNotification()
如下: notificationManager.notify(0, builder.getNotification());
2. .setPriority() 方法不可用
接下来是完整的实现
java文件中
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);Notification.Builder builder = new Notification.Builder(context);builder.setContentTitle("危险警报!!!") .setContentText("您的手机已经被病毒入侵,点击紧急杀毒") .setSmallIcon(R.mipmap.jiaojing) notificationManager.notify(0, builder.build()); //API15以及以下需要把.build()方法需要换成.getNotification()
Notification的点击事件
java代码如下
只需要实例化一个PendingIntent 利用 .setContentIntent()方法实现
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.baidu.com/")); PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0); NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Notification.Builder builder = new Notification.Builder(TongZhiActivity.this); builder.setContentTitle("标题") .setContentText("内容(点击跳转至百度)") .setSmallIcon(R.mipmap.jiaojing) .setContentIntent(pi) .setAutoCancel(true) //点击后关闭通知 .setWhen(System.currentTimeMillis()) ; notificationManager.notify(1, builder.build());
Notification悬浮通知
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.baidu.com/")); PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0); NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Notification.Builder builder = new Notification.Builder(TongZhiActivity.this); builder.setContentTitle("悬浮") .setContentText("悬浮通知") .setSmallIcon(R.mipmap.jiaojing) .setContentIntent(pi) .setAutoCancel(true) //点击后关闭通知 .setWhen(System.currentTimeMillis()) .setDefaults(Notification.DEFAULT_ALL) .setPriority(Notification.PRIORITY_MAX) .setFullScreenIntent(pi, true); notificationManager.notify(3, builder.build());
更多相关文章
- Android(安卓)SDK Manager 更新方法
- Android日期空间(DatePickerDialog)中的年月日不全部显示
- Android(安卓)菜单详解
- 2.3.2 Android(安卓)Studio使用记录——2.快捷键大全
- 【转载】Android事件分发机制完全解析,带你从源码的角度彻底理解(
- Android:关于Window少为人知的一面
- android中常见的错误及解决办法
- 浅谈Java中Collections.sort对List排序的两种方法
- Python list sort方法的具体使用