網站首頁 編程語言 正文
前言
在上一篇通知服務NotificationListenerService使用方法 中,我們已經介紹了如何使用NotificationListenerService來監聽消息通知,在最后我們還模擬了如何實現微信自動搶紅包功能。
那么NotificationListenerService是如何實現系統通知監聽的呢?(本篇源碼分析基于API 32)
NotificationListenerService方法集
NotificationLisenerService是Service的子類
public abstract class NotificationListenerService extends Service
除了Service的方法屬性外,NotificationListenerService還為我們提供了收到通知、通知被移除、連接到通知管理器等方法,如下圖所示。
一般業務中我們只關注有標簽的那四個方法即可。
NotificationListenerService接收流程
既然NotificationListenerService是繼承自Service的,我們先來看它的onBind方法,代碼如下所示。
@Override
public IBinder onBind(Intent intent) {
if (mWrapper == null) {
mWrapper = new NotificationListenerWrapper();
}
return mWrapper;
}
在onBind方法中返回了一個NotificationListenerWrapper實例,NotificationListenerWrapper對象是定義在NotificationListenerService中的一個內部類。主要方法如下所示。
/** @hide */
protected class NotificationListenerWrapper extends INotificationListener.Stub {
@Override
public void onNotificationPosted(IStatusBarNotificationHolder sbnHolder,
NotificationRankingUpdate update) {
StatusBarNotification sbn;
try {
sbn = sbnHolder.get();
} catch (RemoteException e) {
Log.w(TAG, "onNotificationPosted: Error receiving StatusBarNotification", e);
return;
}
if (sbn == null) {
Log.w(TAG, "onNotificationPosted: Error receiving StatusBarNotification");
return;
}
try {
// convert icon metadata to legacy format for older clients
createLegacyIconExtras(sbn.getNotification());
maybePopulateRemoteViews(sbn.getNotification());
maybePopulatePeople(sbn.getNotification());
} catch (IllegalArgumentException e) {
// warn and drop corrupt notification
Log.w(TAG, "onNotificationPosted: can't rebuild notification from " +
sbn.getPackageName());
sbn = null;
}
// protect subclass from concurrent modifications of (@link mNotificationKeys}.
synchronized (mLock) {
applyUpdateLocked(update);
if (sbn != null) {
SomeArgs args = SomeArgs.obtain();
args.arg1 = sbn;
args.arg2 = mRankingMap;
mHandler.obtainMessage(MyHandler.MSG_ON_NOTIFICATION_POSTED,
args).sendToTarget();
} else {
// still pass along the ranking map, it may contain other information
mHandler.obtainMessage(MyHandler.MSG_ON_NOTIFICATION_RANKING_UPDATE,
mRankingMap).sendToTarget();
}
}
...省略onNotificationRemoved等方法
}
NotificationListenerWrapper繼承自INotificationListener.Stub,當我們看到Stub這一關鍵字的時候,就應該知道這里是使用AIDL實現了跨進程通信。
在NotificationListenerWrapper的onNotificationPosted中通過代碼
mHandler.obtainMessage(MyHandler.MSG_ON_NOTIFICATION_POSTED,
args).sendToTarget();
將消息發送出去,handler接受后,又調用NotificationListernerService的onNotificationPosted方法,進而實現通知消息的監聽。代碼如下所示。
private final class MyHandler extends Handler {
public static final int MSG_ON_NOTIFICATION_POSTED = 1;
@Override
public void handleMessage(Message msg) {
if (!isConnected) {
return;
}
switch (msg.what) {
case MSG_ON_NOTIFICATION_POSTED: {
SomeArgs args = (SomeArgs) msg.obj;
StatusBarNotification sbn = (StatusBarNotification) args.arg1;
RankingMap rankingMap = (RankingMap) args.arg2;
args.recycle();
onNotificationPosted(sbn, rankingMap);
} break;
...
}
}
}
那么,消息通知發送時,又是如何與NotificationListenerWrapper通信的呢?
通知消息發送流程
當客戶端發送一個通知的時候,會調用如下所示的代碼
notificationManager.notify(1, notification)
notify又會調用notifyAsUser方法,代碼如下所示
public void notifyAsUser(String tag, int id, Notification notification, UserHandle user)
{
INotificationManager service = getService();
String pkg = mContext.getPackageName();
try {
if (localLOGV) Log.v(TAG, pkg + ": notify(" + id + ", " + notification + ")");
service.enqueueNotificationWithTag(pkg, mContext.getOpPackageName(), tag, id,
fixNotification(notification), user.getIdentifier());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
緊接著又會走到INotificationManager的enqueueNotificationWithTag方法中,enqueueNotificationWithTag是聲明在INotificationManager.aidl文件中的接口
/** {@hide} */
interface INotificationManager
{
@UnsupportedAppUsage
void cancelAllNotifications(String pkg, int userId);
...
void cancelToast(String pkg, IBinder token);
void finishToken(String pkg, IBinder token);
void enqueueNotificationWithTag(String pkg, String opPkg, String tag, int id,
in Notification notification, int userId);
...
}
這個接口是在NotificationManagerService中實現的,接著我們轉到NotificationManagerService中去查看,相關主要代碼如下所示。
@VisibleForTesting
final IBinder mService = new INotificationManager.Stub() {
@Override
public void enqueueNotificationWithTag(String pkg, String opPkg, String tag, int id,
Notification notification, int userId) throws RemoteException {
enqueueNotificationInternal(pkg, opPkg, Binder.getCallingUid(),
Binder.getCallingPid(), tag, id, notification, userId);
}
}
enqueueNotificationWithTag方法會走進enqueueNotificationInternal方法,在方法最后會通過Handler發送一個EnqueueNotificationRunnable,代碼如下所示。
void enqueueNotificationInternal(final String pkg, final String opPkg, final int callingUid,
final int callingPid, final String tag, final int id, final Notification notification,
int incomingUserId, boolean postSilently) {
...
//構造StatusBarNotification,用于分發監聽服務
final StatusBarNotification n = new StatusBarNotification(
pkg, opPkg, id, tag, notificationUid, callingPid, notification,
user, null, System.currentTimeMillis());
// setup local book-keeping
String channelId = notification.getChannelId();
if (mIsTelevision && (new Notification.TvExtender(notification)).getChannelId() != null) {
channelId = (new Notification.TvExtender(notification)).getChannelId();
}
...
// 設置intent的白名點,是否盛典、是否后臺啟動等
if (notification.allPendingIntents != null) {
final int intentCount = notification.allPendingIntents.size();
if (intentCount > 0) {
final long duration = LocalServices.getService(
DeviceIdleInternal.class).getNotificationAllowlistDuration();
for (int i = 0; i < intentCount; i++) {
PendingIntent pendingIntent = notification.allPendingIntents.valueAt(i);
if (pendingIntent != null) {
mAmi.setPendingIntentAllowlistDuration(pendingIntent.getTarget(),
ALLOWLIST_TOKEN, duration,
TEMPORARY_ALLOWLIST_TYPE_FOREGROUND_SERVICE_ALLOWED,
REASON_NOTIFICATION_SERVICE,
"NotificationManagerService");
mAmi.setPendingIntentAllowBgActivityStarts(pendingIntent.getTarget(),
ALLOWLIST_TOKEN, (FLAG_ACTIVITY_SENDER | FLAG_BROADCAST_SENDER
| FLAG_SERVICE_SENDER));
}
}
}
}
...
mHandler.post(new EnqueueNotificationRunnable(userId, r, isAppForeground));
}
EnqueueNotificationRunnable源碼如下所示。
protected class EnqueueNotificationRunnable implements Runnable {
private final NotificationRecord r;
private final int userId;
private final boolean isAppForeground;
EnqueueNotificationRunnable(int userId, NotificationRecord r, boolean foreground) {
this.userId = userId;
this.r = r;
this.isAppForeground = foreground;
}
@Override
public void run() {
synchronized (mNotificationLock) {
...
//將通知加入隊列
mEnqueuedNotifications.add(r);
scheduleTimeoutLocked(r);
...
if (mAssistants.isEnabled()) {
mAssistants.onNotificationEnqueuedLocked(r);
mHandler.postDelayed(new PostNotificationRunnable(r.getKey()),
DELAY_FOR_ASSISTANT_TIME);
} else {
mHandler.post(new PostNotificationRunnable(r.getKey()));
}
}
}
}
在EnqueueNotificationRunnable最后又會發送一個PostNotificationRunable,
PostNotificationRunable源碼如下所示。
protected class PostNotificationRunnable implements Runnable {
private final String key;
PostNotificationRunnable(String key) {
this.key = key;
}
@Override
public void run() {
synchronized (mNotificationLock) {
try {
...
//發送通知
if (notification.getSmallIcon() != null) {
StatusBarNotification oldSbn = (old != null) ? old.getSbn() : null;
mListeners.notifyPostedLocked(r, old);
if ((oldSbn == null || !Objects.equals(oldSbn.getGroup(), n.getGroup()))
&& !isCritical(r)) {
mHandler.post(new Runnable() {
@Override
public void run() {
mGroupHelper.onNotificationPosted(
n, hasAutoGroupSummaryLocked(n));
}
});
} else if (oldSbn != null) {
final NotificationRecord finalRecord = r;
mHandler.post(() -> mGroupHelper.onNotificationUpdated(
finalRecord.getSbn(), hasAutoGroupSummaryLocked(n)));
}
} else {
//...
}
} finally {
...
}
}
}
}
從代碼中可以看出,PostNotificationRunable類中會調用notifyPostedLocked方法,這里你可能會有疑問:這里分明判斷notification.getSmallIcon()是否為null,不為null時才會進入notifyPostedLocked方法。為什么這里直接默認了呢?這是因為在Android5.0中規定smallIcon不可為null,且NotificationListenerService僅適用于5.0以上,所以這里是必然會執行到notifyPostedLocked方法的。
其方法源碼如下所示。
private void notifyPostedLocked(NotificationRecord r, NotificationRecord old,
boolean notifyAllListeners) {
try {
// Lazily initialized snapshots of the notification.
StatusBarNotification sbn = r.getSbn();
StatusBarNotification oldSbn = (old != null) ? old.getSbn() : null;
TrimCache trimCache = new TrimCache(sbn);
//循環通知每個ManagedServiceInfo對象
for (final ManagedServiceInfo info : getServices()) {
...
mHandler.post(() -> notifyPosted(info, sbnToPost, update));
}
} catch (Exception e) {
Slog.e(TAG, "Could not notify listeners for " + r.getKey(), e);
}
}
notifyPostedLocked方法最終會調用notifyPosted方法,我們再來看notifyPosted方法。
private void notifyPosted(final ManagedServiceInfo info,
final StatusBarNotification sbn, NotificationRankingUpdate rankingUpdate) {
final INotificationListener listener = (INotificationListener) info.service;
StatusBarNotificationHolder sbnHolder = new StatusBarNotificationHolder(sbn);
try {
listener.onNotificationPosted(sbnHolder, rankingUpdate);
} catch (RemoteException ex) {
Slog.e(TAG, "unable to notify listener (posted): " + info, ex);
}
}
notifyPosted方法,最終會調用INotificationListerner的onNotificationPosted方法,這樣就通知到了NotificationListenerService的onNotificationPosted方法。
上述方法的流程圖如下圖所示。
NotificationListenerService注冊
在NotificationListenerService中通過registerAsSystemService方法注冊服務,代碼如下所示。
@SystemApi
public void registerAsSystemService(Context context, ComponentName componentName,
int currentUser) throws RemoteException {
if (mWrapper == null) {
mWrapper = new NotificationListenerWrapper();
}
mSystemContext = context;
INotificationManager noMan = getNotificationInterface();
mHandler = new MyHandler(context.getMainLooper());
mCurrentUser = currentUser;
noMan.registerListener(mWrapper, componentName, currentUser);
}
registerAsSystemService方法將NotificationListenerWrapper對象注冊到NotificationManagerService中。如此就實現了對系統通知的監聽。
總結
NotificationListenerService實現對系統通知的監聽可以概括為三步:
- NotificationListenerService將 NotificationListenerWrapper注冊到NotificationManagerService中。
- 當有通知被發送時 ,NotificationManagerService跨進程通知到每個NotificationListenerWrapper。
- NotificationListenerWrapper中信息由NotificationListenerService類中的Handler中處理,從而調用NotificationListenerService中對應的回調方法。
原文鏈接:https://juejin.cn/post/7166864980632371207
相關推薦
- 2023-05-30 Pandas.concat連接DataFrame,Series的示例代碼_python
- 2022-08-17 VMWare虛擬機為Windows?Server?2008設置靜態IP的方法_VMware
- 2022-06-01 c++深入淺出講解堆排序和堆_C 語言
- 2021-11-30 Linux?Autofs自動掛載服務安裝部署教程_Linux
- 2022-07-11 UVM中超時退出set_timeout函數
- 2022-03-08 android?studio組件通信:Intend啟動Activity接收返回結果_Android
- 2022-11-23 shell腳本設置日志格式的方法_linux shell
- 2022-10-13 python中arrow庫用法大全_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支