Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 使用 NotificationListenerService 監聽系統所有通知

編輯:關於 Android 程式設計

NotificationListenerService 是 Android 4.3(API 18)引入的一項系統服務。它的運作模式是:由系統主動調起,每當任意應用發出通知或有用戶移除通知時,系統就把通知的動作與內容回調給這個服務。它也因此成為「通知同步」「通知增強」「 Wear 手錶中轉」這類應用的基礎能力。

一、在 Manifest 中聲明並申請綁定權限

繼承該服務之前,必須先在 AndroidManifest.xml 中聲明,並掛上專用的綁定權限:

<service
    android:name=".NotificationListener"
    android:label="@string/service_name"
    android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
    <intent-filter>
        <action android:name=
            "android.service.notification.NotificationListenerService" />
    </intent-filter>
</service>

這裡有個關鍵點常被漏掉:intent-filter 中必須声明 android.service.notification.NotificationListenerService 這個 action,系統才知道要把你的服務列入候選名單。

聲明完成後,系統設定中就會出現對應的開關。以 MIUI 為例,路徑是「設定 → 安全與隱私 → 通知讀取權限」;原生 Android 則在「設定 → 通知 → 通知訪問」。

注意:這個權限用戶只能手動開啟,無法通過 dialog 或權限請求彈窗自動獲得。實務上通常引導用戶跳轉到 Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS 頁面自行開啟。

二、實現兩個核心回調方法

public class NotificationCollectorService extends NotificationListenerService {

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        Log.i("zpf", "open-----" + sbn.toString());
    }

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        Log.i("zpf", "shut-----" + sbn.toString());
    }
}

這兩個方法是抽象方法,必須實現:

  • onNotificationPosted():有應用發出新通知時觸發
  • onNotificationRemoved():通知被清除(用戶滑掉或應用自行 cancel)時觸發

三、從 StatusBarNotification 中挖數據

參數 StatusBarNotification 承載了通知的全部信息,常用途徑包括:

// 發送方包名,可用來做白名單/黑名單過濾
String packageName = sbn.getPackageName();

// 通知 ID 與 tag
String tag = sbn.getTag();
int id = sbn.getId();

// 通知本體,這裡能拿到標題、內容、時間等
Notification notification = sbn.getNotification();
CharSequence title = notification.extras.getCharSequence("android.title");
CharSequence text  = notification.extras.getCharSequence("android.text");
long postTime = notification.when;

// 點擊通知時要啟動的 Intent(PendingIntent)
PendingIntent pendingIntent = notification.contentIntent;

notification.extras 是一個 Bundle,不同版本的鍵名略有差異,因此更穩健的做法是判斷通知是否實現了 NotificationCompat.MessagingStyle 等樣式接口,或直接讀取 extras 並做空值保護。

四、典型應用場景

最經典的用法莫過於 Android Wear 的通知中轉:手機端用這個服務攔截所有通知,再透過 Data Layer API 或 MessageApi 同步到手表。此外還有:

  • 通知分類統計:按包名聚合,幫用戶分析哪個應用打擾最多。
  • 關鍵信息提取:例如自動識別短信驗證碼並提供一鍵複製。
  • 通知增強:為通知補充快捷操作按鈕。

五、必須知道的限制與注意事項

  • 隱私與上架審核:這個權限能讀取用戶所有通知(可能含驗證碼、聊天內容),Google Play 對使用它的應用審核極嚴,必須提交核心功能說明,濫用會導致下架。
  • 拿不到通知的實際內容圖片:部分通知只提供 Icon 而非完整 Bitmap。
  • 生命週期由系統掌控:服務可能在內存緊張時被回收,重要數據要及時持久化,不要只存在內存裡。
  • 記得判空:notification.extras 在個別自定義通知中可能為 null,直接取值會崩潰。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved