Android 12.0 应用中监听系统收到的通知

Android 12.0 通知简介icon-default.png?t=N7T8https://blog.csdn.net/Smile_729day/article/details/135502031?spm=1001.2014.3001.5502 

1. 需求

在系统内置应用中或者在第三方应用中,获取Android系统收到的通知的内容.

2. NotificationListenerService 接口

Android 系统预留了专门的API, 即 NotificationListenerService 接口,它的源码路径为:

源码路径 : /frameworks/base/core/java/android/service/notification/NotificationListenerService.javapublic abstract class NotificationListenerService extends Service {......

3. 实现 NotificationListenerService

NotificationListenerService 是抽象类,通过在 Service 中实现该抽象类,并实现需要的接口,代码如下:

public class MyNotificationListenerService extends NotificationListenerService {//当系统收到新的通知时,会触发该接口@Overridepublic void onNotificationPosted(StatusBarNotification sbn) {addAlienNotificationInfo(sbn); //获取通知的内容}//当系统移除通知时,即在通知列表中清除通知时,或者卸载应用时,该应用包名下的通知都会被清除,也同样会会触发该接口@Overridepublic void onNotificationRemoved(StatusBarNotification sbn) {super.onNotificationRemoved(sbn);}
}

上面两个接口,第一个是监听系统新通知,第二个是监听系统通知清除,如果看过Android Systemui 中有关通知的内容,就会发现,System UI 对通知的显示和通知的清除,同样也是继承该API.

下面,分析当系统收到新通知时,如何解析出通知里的内容.

4. 获取通知内容

   private void addAlienNotificationInfo(StatusBarNotification sbn) {String packageName = sbn.getPackageName();//获取发送通知的包名Notification notification = sbn.getNotification(); //获得一个Notification对象Bundle extras = notification.extras;RemoteViews contentView = notification.contentView;//ApplicationInfo appInfo = extras.getParcelable(NotificationCompat.EXTRA_BUILDER_APPLICATION_INFO);//如果是系统内置应用,可以获取到ApplicationInfo ,后面会有解释//String appName = appInfo.loadLabel(mPm).toString(); //如果是系统内置的应用,可以通过ApplicationInfo对象获取通知发送这条通知的应用名String category = notification.category;String channelId = notification.getChannelId();//String className = getNotificationClassName(notification);//如果是系统内置应用,可以获取到通知中设置的Intent,后面会有解释int color = notification.color;//通知setColor()设置的颜色boolean defaultVibrate = (notification.vibrate == null) ? true : false;String notificationVibrationString = Arrays.toString(notification.vibrate);int importance = notification.priority; //通知的重要性String key = sbn.getKey();//通知的Key,删除通知时,需要通过Key来确定删除哪条通知Icon myLargeIconToIcon = extras.getParcelable(Notification.EXTRA_LARGE_ICON);//获取通知设置的大图片,即setLargeIcon() ,int ledColor = notification.ledARGB;//通知led灯颜色String sound = (notification.sound != null) ? notification.sound.toString() : null;int progress = extras.getInt(Notification.EXTRA_PROGRESS);//当前进度值int progressMax = extras.getInt(Notification.EXTRA_PROGRESS_MAX);//设定的最大进度值boolean progressIndeterminate = extras.getBoolean(Notification.EXTRA_PROGRESS_INDETERMINATE);//是否在通知中显示进度值int flagsToCheck = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;boolean resident = (notification.flags & flagsToCheck) != 0;//是否是常驻通知(前台&onging),类似于音乐应用,String smallIcon = notification.getSmallIcon().toString();//通知设置的smallIcon()String title = (String) extras.get(Notification.EXTRA_TITLE);//通知标题String subText = (String) extras.get(Notification.EXTRA_SUB_TEXT);//通知附加内容String text = (String) extras.get(Notification.EXTRA_TEXT);//通知内容boolean userRemovable = (notification.flags & Notification.FLAG_AUTO_CANCEL) != 0; //是否可移除通知,即 setAutoCancel(boolean autoCancel) 中设定的值long when = notification.when;//通知的时间String template = getNotificationTemplate(notification);//获取通知的类型,下面会详细介绍//BigTextStyle通知中,bigText的内容String bigText = (String) extras.getCharSequence(Notification.EXTRA_BIG_TEXT);    //BigPictureStyle通知中设置的大图片Bitmap picture_extraBitmap = extras.getParcelable(Notification.EXTRA_PICTURE);//状态栏通知列表中,折叠时是否显示图片,注意:该属性在Android12上有,Android11上没有,boolean mShowBigPictureWhenCollapsed = extras.getBoolean(Notification.EXTRA_SHOW_BIG_PICTURE_WHEN_COLLASED);//通过下面的方法也可以查看通知中的设置的全部参数for(String mykey : notification.extras.keySet()){String ex = " " + mykey +" => " + notification.extras.get(mykey)+ ";";Log.d(TAG,"ex="+ex);}
}

(1) 获取ApplicationInfo

      上面在获取通知的ApplicationInfo时,使用了 Notification.EXTRA_BUILDER_APPLICATION_INFO,该值不对系统外开放,如下源码所示:

源码路径:/frameworks/base/core/java/android/app/Notification.java/*** @hide*/public static final String EXTRA_BUILDER_APPLICATION_INFO = "android.appInfo";

(2) getNotificationClassName(notification)

        上面还涉及到了getNotificationClassName(notification) 获取这条通知中通过PendingIntent中设置的 Intent ,方法中用到了不对外使用的方法,代码如下:

 private String getNotificationClassName(Notification notification) {if (notification.contentIntent != null) {Intent intent = notification.contentIntent.getIntent();if (intent != null && intent.getComponent() != null) {return intent.getComponent().getClassName();}}return null;}

(3) 获取 PendingIntent 对象

         其中的 notification.contentIntent 是获取 通知中的 PendingIntent 对象,源码如下:

源码路径:/frameworks/base/core/java/android/app/Notification.java /*** 单击展开的状态条目时要执行的意图。*/public PendingIntent contentIntent;
(4) PendingIntent.getIntent()

         接着再通过调用 PendingIntent 对象中的 getIntent() 来获取通知中设定的 Intent, 源码如下:

源码路径: /frameworks/base/core/java/android/app/PendingIntent.java/*** @hide (该方法不对外公开)* 返回 PendingIntent 中的 Intent .*/@UnsupportedAppUsagepublic Intent getIntent() {try {return ActivityManager.getService().getIntentForIntentSender(mTarget);} catch (RemoteException e) {throw e.rethrowFromSystemServer();}}

 由于源码中有@hide,表明该方法不对第三方应用开放,所以如果是系统内置的应用,则可以使用.

(5) getNotificationTemplate(Notification notification) 

         Android中定义了一些通知模板,常用的如: BigPictureStyle , BigTextStyle 等,代码如下:

/*** 返回通知的类型,如果没有使用,则返回null.* 返回的类型,如: "android.app.Notification$BigTextStyle",* 因此需要对字符串进行截取,如最后返回: "BigTextStyle"
*/private String getNotificationTemplate(Notification notification) {String template = notification.extras.getString(Notification.EXTRA_TEMPLATE);if (template != null) {int indexOf = template.indexOf('$');return template.substring(indexOf + 1);}return null;}

5. 通知的清除 

当通知被清除时,会调用 onNotificationRemoved(StatusBarNotification sbn) 方法,其中的参数 sbn 代表被删除的通知.可以在该方法里做一些删除后的工作.

6 . NotificationListenerService 中其他有用的方法

(1) 获取有效的通知 : getActiveNotifications() 

源码路径: /frameworks/base/core/java/android/service/notification/NotificationListenerService.java/*** 请求未完成通知的列表(即那些对当前用户)。** @return 活动通知数组,按自然顺序排序。*/public StatusBarNotification[] getActiveNotifications() {StatusBarNotification[] activeNotifications = getActiveNotifications(null, TRIM_FULL);return activeNotifications != null ? activeNotifications : new StatusBarNotification[0];}

(2) 删除指定单条通知 : cancelNotification(String key)   

源码路径: /frameworks/base/core/java/android/service/notification/NotificationListenerService.java /*** 删除指定的一条通知**/public final void cancelNotification(String key) {if (!isBound()) return;//是否绑定了NotificationListenerService服务try {getNotificationInterface().cancelNotificationsFromListener(mWrapper,new String[] { key });} catch (android.os.RemoteException ex) {Log.v(TAG, "Unable to contact notification manager", ex);}}

 (3) 删除指定的多条通知: cancelNotifications(String[] keys)

源码路径: /frameworks/base/core/java/android/service/notification/NotificationListenerService.java /*** 删除 数组 keys 中指定key的通知*/public final void cancelNotifications(String[] keys) {if (!isBound()) return;try {getNotificationInterface().cancelNotificationsFromListener(mWrapper, keys);} catch (android.os.RemoteException ex) {Log.v(TAG, "Unable to contact notification manager", ex);}}

(4) 清除所有通知,对应于通知列表下的 清除所有通知的按钮功能: cancelAllNotifications()

  /*** 通知通知管理器清除所有通知* 类似于Android状态栏和通知面板调用 UI 的“全部关闭”功能* 收到通知后,通知管理器实际上会删除所有活动通知* 并且收到多个 {@link #onNotificationRemoved(StatusBarNotification)} 回调。*/public final void cancelAllNotifications() {cancelNotifications(null /*all*/);}

至此,关于监听系统通知介绍完毕,谢谢观看!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/444180.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【脑电信号处理与特征提取】P7-贾会宾:基于EEG/MEG信号的大尺度脑功能网络分析

基于EEG/MEG信号的大尺度脑功能网络分析 Q: 什么是基于EEG/MEG信号的大尺度脑功能网络分析? A: 基于脑电图(EEG)或脑磁图(MEG)信号的大尺度脑功能网络分析是一种研究大脑活动的方法,旨在探索脑区之间的功能…

075:vue+mapbox 利用高德地址逆转换,点击地图,弹出地址信息

第075个 点击查看专栏目录 本示例的目的是介绍演示如何在vue+mapbox中利用高德逆地理编码,点击地图,弹出某点坐标和地址信息。这里要仔细阅读高德地图的逆编码API,同时要注意的是,这种转换在中国很好用,到了欧美国家就不好使了。同时这个底图是天地图的图像和标记。 直接…

Qt 5.9.4 转 Qt 6.6.1 遇到的问题总结(三)

1.QSet: toList 中的toList 函数已不存在,遇到xx->toList改成直接用,如下: 2.开源QWT 图形库中QwtDial中的 setPenWidth 变成 setPenWidthF函数。 3.QDateTime 中无setTime_t 改为了setSecsSinceEpoch函数。 4.QRegExp 类已不存在 可以用Q…

vue3/vue2中自定义指令不可输入小数点.

import { directive } from vueconst noDecimal {mounted(el) {el.addEventListener(keypress, (e) > {if (e.key .) {e.preventDefault() }})} }// 使用自定义指令 directive(no-decimal, noDecimal)使用 标签上添加 v-no-decimal <el-input…

【微服务】Spring Boot集成ELK实用案例

推荐一款我一直在用国内很火的AI网站&#xff0c;包含GPT3.5/4.0、文心一言、通义千问、智谱AI等多个AI模型&#xff0c;支持PC、APP、VScode插件同步使用&#xff0c;点击链接跳转->ChatGPT4.0中文版 一、前言 在现代软件开发中&#xff0c;微服务架构已成为一种流行趋势。…

使用 axios 请求库,设置请求拦截

什么是 axios&#xff1f; 基于promise网络请求库&#xff0c;可以同构&#xff08;同一套代码可以运行在浏览器&#xff09;&#xff0c;在服务端&#xff0c;使用原生node.js的http模块&#xff0c;在客户端&#xff08;浏览器&#xff09;中&#xff0c;使用XMLHttpRequests…

轻松录制视频,WPS录屏功能全攻略

“有人知道wps怎么录屏吗&#xff1f;老师要求我们录制一段视频&#xff0c;是关于课堂教学的&#xff0c;可是我不会录制文档&#xff0c;眼看就快到提交的时间了&#xff0c;现在真的很着急&#xff0c;希望大家帮帮我&#xff01;” 随着信息技术的发展&#xff0c;录制屏幕…

探索设计模式的魅力:精准解读桥接模式-用桥接模式构建可扩展的软件系统

设计模式专栏&#xff1a;http://t.csdnimg.cn/nolNS 目录 一、了解桥接模式&#xff1a;探索抽象和实现的分离 1.1 开-闭原则 1.2 组合/聚合复用原则 1.3 定义 1.4 用意 1.5 基本思想 1.6 组成部分 1.7 桥梁模式的示意性系统的结构图 二、桥接模式的优势&#xff1a…

vue-cli项目运行流程介绍

一、前言 ​ 本文介绍 vue-cli搭建的项目运行流程&#xff0c;基于已经搭建好的基础项目。关于 vue-cli 构建项目的详细流程&#xff0c;可参考博文&#xff1a;使用vue脚手架构建项目 二、main.js 项目运行 会加载入口文件 main.js /* html文件中&#xff0c;通过script …

uWSGI、灰度发布、网站数据指标分析、网站限速

1 案例1&#xff1a;部署Python网站项目 1.1 问题 配置Nginx使其可以将动态访问转交给uWSGI&#xff1a; 1.2 方案 安装Python工具及依赖 安装uWSGI并编写配置文件 1.3 步骤 实现此案例需要按照如下步骤进行。 步骤一&#xff1a; 首先$教学资料目录/python拷贝到虚拟…

D2076——低压立体声耳机放大电路,适用于便携式小型收音机或立体声耳机作双通道或BIL应用,外接元件少,采用SOP8封装

D2076是一块双通道音频功率放大器&#xff0c;最低工作电压可到1.0V. 适用于便携式小型收音机或立体声耳机作双通道或BIL应用。 主要特点&#xff1a; ● BTL工作 Po90mW (典型值)。 ● 外接元件少 ● 通过外接晶体管作为耳机功率放大。 ● 工作电压低 (1.0V最小值)。 ● 工…

【计算机网络】Socket的SO_REUSEADDR选项与TIME_WAIT

SO_REUSEADDR用于设置套接字的地址重用。当一个套接字关闭后&#xff0c;它的端口可能会在一段时间内处于TIME_WAIT状态&#xff0c;此时无法立即再次绑定相同的地址和端口。使用SO_REUSEADDR选项可以允许新的套接字立即绑定到相同的地址和端口&#xff0c;即使之前的套接字仍处…