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

Android 4.4 NotificationListenerService 使用詳解與原理分析(一)

編輯:關於 Android 程式設計

概況

Android 在 4.3(API 18)中引入了 NotificationListenerService。根據官方開發者文檔的說法,當系統收到新通知或通知被刪除時,會觸發該服務的回調方法。而 Android 4.4 又新增了 Notification.extras 字段,這意味著我們可以直接獲取通知的具體內容——在這之前,想拿到通知標題、文本,只能無奈地求助反射。

重要關係

三方 App 使用 NotificationListenerService,主要目的就是為了獲取系統通知的相關信息:通知的新增與刪除、當前通知數量、通知的具體內容等。這些信息通過 NotificationListenerService 自身的方法,配合 StatusBarNotification 對象來獲取。

NotificationListenerService 主要方法:

cancelAllNotifications():刪除系統中所有可被清除的通知;
cancelNotification(String pkg, String tag, int id):刪除某一條具體通知;
getActiveNotifications():返回當前系統所有通知,類型為 StatusBarNotification[];
onNotificationPosted(StatusBarNotification sbn):系統收到新通知後觸發;
onNotificationRemoved(StatusBarNotification sbn):通知被刪除後觸發;

有了這些方法,就可以在應用中讀取並操作系統通知。而 StatusBarNotification 對象則提供了更細粒度的數據。

StatusBarNotification 主要方法:

getId():返回通知對應的 id;
getNotification():返回通知對象本身;
getPackageName():返回發起通知的應用包名;
getPostTime():返回通知發出的時間;
getTag():返回通知的 Tag,未設置時為 null;
getUserId():返回 UserId,用於多用戶場景;
isClearable():該通知是否可被清除(受 FLAG_ONGOING_EVENT、FLAG_NO_CLEAR 影響);
isOngoing():檢查 flag 是否為 FLAG_ONGOING_EVENT;

使用簡介

正確使用 NotificationListenerService 需要注意三步。

(1) 新建一個類並繼承 NotificationListenerService,重寫兩個重要方法

public class NotificationMonitor extends NotificationListenerService {

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        Log.i("SevenNLS", "Notification posted");
    }

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        Log.i("SevenNLS", "Notification removed");
    }
}

(2) 在 AndroidManifest.xml 中註冊 Service 並聲明權限

<service
    android:name=".NotificationMonitor"
    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:permission 則保證只有系統能綁定它,防止第三方惡意調用。

(3) 開啟 NotificationMonitor 的監聽功能

完成前兩步、把程序安裝到手機後,你會發現它仍然收不到任何通知。還需要進入「設置 > 安全 > 通知訪問」,勾選 NotificationMonitor。此後系統一旦收到新通知或刪除通知,就會打印出對應的日志。

這裡有個容易被忽略的細節:如果手機上根本沒有安裝使用 NotificationListenerService 的 App,「通知訪問」這一項是不會顯示出來的。源碼 packages/apps/Settings/src/com/android/settings/SecuritySettings.java 中可以看到,當 listener 數量為 0 時,直接把該 Preference 從列表裡移除:

mNotificationAccess = findPreference(KEY_NOTIFICATION_ACCESS);
if (mNotificationAccess != null) {
    final int total = NotificationAccessSettings.getListenersCount(mPM);
    if (total == 0) {
        if (deviceAdminCategory != null) {
            deviceAdminCategory.removePreference(mNotificationAccess);
        }
    } else {
        final int n = getNumEnabledNotificationListeners();
        if (n == 0) {
            mNotificationAccess.setSummary(getResources().getString(
                    R.string.manage_notification_access_summary_zero));
        } else {
            mNotificationAccess.setSummary(String.format(
                    getResources().getQuantityString(
                            R.plurals.manage_notification_access_summary_nonzero, n, n)));
        }
    }
}

使用詳解

按前面的步驟已經能跑通基本功能,但真正落到應用裡,要考慮的事情還不少:

1. 如何檢測應用已開啟 Notification access 監聽功能? 若未激活,需要提示用戶開啟。
2. 能不能主動跳轉到 Notification access 監聽頁面? 如果能自動跳轉,可省掉用戶大量翻找操作。
3. 如何與 NotificationListenerService 交互? 它雖然是 Service,但交互方式與普通 Service 有本質差別。
4. 使用過程中有哪些坑? 下文會逐條給出解決方案。

程序運行截圖

圖 1 程序運行截圖

示例介紹

NotificationListenerDemo 用於獲取系統當前通知信息,並支持手動創建「可清除通知」、逐條刪除、一次性刪除,以及展示當前所有活動通知。它實際上回答了上面提出的各項疑問。

圖 2 主界面

功能分析 1:如何檢測是否已開啟監聽

程序啟動時執行檢測,若用戶未 Enable,則彈出確認框,點擊「確定」跳轉到設置頁。

圖 3 首次啟動檢測

原理是:一旦開啟,系統會把包名等信息寫入 SettingsProvider 數據庫的 enabled_notification_listeners 字段。因此只要讀出該值並過濾,即可判斷本應用是否在列:

private static final String ENABLED_NOTIFICATION_LISTENERS =
        "enabled_notification_listeners";

private boolean isEnabled() {
    String pkgName = getPackageName();
    final String flat = Settings.Secure.getString(
            getContentResolver(), ENABLED_NOTIFICATION_LISTENERS);
    if (!TextUtils.isEmpty(flat)) {
        final String[] names = flat.split(":");
        for (int i = 0; i < names.length; i++) {
            final ComponentName cn = ComponentName.unflattenFromString(names[i]);
            if (cn != null) {
                if (TextUtils.equals(pkgName, cn.getPackageName())) {
                    return true;
                }
            }
        }
    }
    return false;
}

返回的 flat 中若包含本應用包名,即說明已開啟,反之則未開啟。

功能分析 2:主動跳轉到監聽設置頁

查源碼可知,Notification access 界面接收 action 為 android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS 的 Intent。因此一行代碼就能跳轉,省去找路之苦:

private static final String ACTION_NOTIFICATION_LISTENER_SETTINGS =
        "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS";

private void openNotificationAccess() {
    startActivity(new Intent(ACTION_NOTIFICATION_LISTENER_SETTINGS));
}

功能分析 3:如何與 NotificationListenerService 交互

核心方法是 onNotificationPosted、onNotificationRemoved、cancelNotification、cancelAllNotifications。它們都是 public 的,那是不是拿到 Service 對象就能直接調用?怎麼拿到 Service 對象?

顯然需要 Binder,也就是要用 bindService(),把 onServiceConnected 回調裡的 IBinder 轉型成 Service 對象。直覺的測試代碼如下:

// 在 MainActivity.onCreate 中綁定 NotificationMonitor
bindService(new Intent(this, NotificationMonitor.class), new ServiceConnection() {
    @Override
    public void onServiceDisconnected(ComponentName arg0) { }

    @Override
    public void onServiceConnected(ComponentName arg0, IBinder arg1) {
        NotificationMonitor.MyBinder localBinder = (MyBinder) arg1;
        NotificationMonitor mMonitor = localBinder.getService();
    }
}, BIND_AUTO_CREATE);
public class NotificationMonitor extends NotificationListenerService {

    private MyBinder mBinder = new MyBinder();

    public class MyBinder extends Binder {
        public NotificationMonitor getService() {
            return NotificationMonitor.this;
        }
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return mBinder;
    }

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        getActiveNotifications();
        cancelAllNotifications();
    }

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) { }
}

很遺憾,這樣做是行不通的。原因需要從源碼看起。NotificationListenerService 的 onBind 是這樣寫的:

@Override
public IBinder onBind(Intent intent) {
    if (mWrapper == null) {
        mWrapper = new INotificationListenerWrapper();
    }
    return mWrapper;
}

其中 INotificationListenerWrapper 是它的內部類:

private class INotificationListenerWrapper extends INotificationListener.Stub

而我們的 NotificationMonitor 繼承自它,默認的 onBind 直接調父類:

@Override
public IBinder onBind(Intent intent) {
    return super.onBind(intent);
}

注意這裡的特殊之處:一般 Service 的 onBind 要麼返回 null,要麼返回自己構造的 Binder,而這裡返回的是父類準備好的 INotificationListenerWrapper。這說明Binder 對象已經被系統指定了,不能再換成別的。你若非要換,那麼 INotificationListenerWrapper 提供的能力就全部失效——系統與你的服務之間的通訊通道斷了,回調自然也不會再來。

換句話說,只有兩個選擇:要麼老老實實用系統提供的 Binder 與方法,要麼把 NotificationMonitor 當一個普通 Service 用,但系統能力全部放棄。

那正確姿势是什麼?既然 Service 內部可以正常調用 getActiveNotifications() 等方法,那就讓它把通知狀態的變化與數據都收集起來,用 static 變量存儲;MainActivity 需要展示時直接讀取即可。而 MainActivity 想控制通知的刪除(單條 / 全部),則通過廣播發送指令給 NotificationMonitor 處理。

圖 4 結構類圖

NotificationMonitor 關鍵代碼:

public class NotificationMonitor extends NotificationListenerService {

    private static final String TAG = "SevenNLS";
    private static final String TAG_PRE =
            "[" + NotificationMonitor.class.getSimpleName() + "] ";
    private static final int EVENT_UPDATE_CURRENT_NOS = 0;

    public static final String ACTION_NLS_CONTROL =
            "com.seven.notificationlistenerdemo.NLSCONTROL";

    /** 用於存儲當前所有 Notification 的 StatusBarNotification 數組 */
    public static List<StatusBarNotification[]> mCurrentNotifications =
            new ArrayList<StatusBarNotification[]>();
    public static int mCurrentNotificationsCounts = 0;

    /** 收到新通知後記錄 */
    public static StatusBarNotification mPostedNotification;
    /** 刪除通知後記錄 */
    public static StatusBarNotification mRemovedNotification;

    private CancelNotificationReceiver mReceiver = new CancelNotificationReceiver();

    private Handler mMonitorHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EVENT_UPDATE_CURRENT_NOS:
                    updateCurrentNotifications();
                    break;
                default:
                    break;
            }
        }
    };

    class CancelNotificationReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action;
            if (intent != null && intent.getAction() != null) {
                action = intent.getAction();
                if (action.equals(ACTION_NLS_CONTROL)) {
                    String command = intent.getStringExtra("command");
                    if (TextUtils.equals(command, "cancel_last")) {
                        // 每次刪除最後一條
                        if (mCurrentNotifications != null
                                && mCurrentNotificationsCounts >= 1) {
                            StatusBarNotification sbnn =
                                    getCurrentNotifications()[mCurrentNotificationsCounts - 1];
                            cancelNotification(
                                    sbnn.getPackageName(), sbnn.getTag(), sbnn.getId());
                        }
                    } else if (TextUtils.equals(command, "cancel_all")) {
                        // 刪除所有通知
                        cancelAllNotifications();
                    }
                }
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_NLS_CONTROL);
        registerReceiver(mReceiver, filter);
        // onCreate 時第一次調用 getActiveNotifications()
        mMonitorHandler.sendMessage(
                mMonitorHandler.obtainMessage(EVENT_UPDATE_CURRENT_NOS));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return super.onBind(intent);
    }

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        // 系統收到新通知後,更新列表
        updateCurrentNotifications();
        mPostedNotification = sbn;

        // 通過 extras 可以獲取 Notification 的詳細信息
        // Bundle extras = sbn.getNotification().extras;
        // String notificationTitle = extras.getString(Notification.EXTRA_TITLE);
        // CharSequence notificationText = extras.getCharSequence(Notification.EXTRA_TEXT);
        // CharSequence notificationSubText = extras.getCharSequence(Notification.EXTRA_SUB_TEXT);
        // Bitmap notificationLargeIcon =
        //         (Bitmap) extras.getParcelable(Notification.EXTRA_LARGE_ICON);
        // Bitmap notificationSmallIcon =
        //         (Bitmap) extras.getParcelable(Notification.EXTRA_SMALL_ICON);
    }

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        updateCurrentNotifications();
        mRemovedNotification = sbn;
    }

    private void updateCurrentNotifications() {
        try {
            StatusBarNotification[] activeNos = getActiveNotifications();
            if (mCurrentNotifications.size() == 0) {
                mCurrentNotifications.add(null);
            }
            mCurrentNotifications.set(0, activeNos);
            mCurrentNotificationsCounts = activeNos.length;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** 獲取當前狀態欄顯示通知總數 */
    public static StatusBarNotification[] getCurrentNotifications() {
        if (mCurrentNotifications.size() == 0) {
            return null;
        }
        return mCurrentNotifications.get(0);
    }
}

MainActivity 負責界面展示與交互,關鍵代碼:

public class MainActivity extends Activity {

    private static final int EVENT_SHOW_CREATE_NOS = 0;
    private static final int EVENT_LIST_CURRENT_NOS = 1;

    private static final String ENABLED_NOTIFICATION_LISTENERS =
            "enabled_notification_listeners";
    private static final String ACTION_NOTIFICATION_LISTENER_SETTINGS =
            "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS";

    private boolean isEnabledNLS = false;
    private TextView mTextView;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EVENT_SHOW_CREATE_NOS:
                    showCreateNotification();
                    break;
                case EVENT_LIST_CURRENT_NOS:
                    listCurrentNotification();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView) findViewById(R.id.textView);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 判斷是否有開啟 Notification access
        isEnabledNLS = isEnabled();
        if (!isEnabledNLS) {
            showConfirmDialog();
        }
    }

    public void buttonOnClicked(View view) {
        mTextView.setTextColor(Color.BLACK);
        switch (view.getId()) {
            case R.id.btnCreateNotify:
                createNotification(this);
                // 延遲 50ms 再刷新,確保系統已完成回調
                mHandler.sendMessageDelayed(
                        mHandler.obtainMessage(EVENT_SHOW_CREATE_NOS), 50);
                break;
            case R.id.btnClearLastNotify:
                clearLastNotification();
                mHandler.sendMessageDelayed(
                        mHandler.obtainMessage(EVENT_LIST_CURRENT_NOS), 50);
                break;
            case R.id.btnClearAllNotify:
                clearAllNotifications();
                mHandler.sendMessageDelayed(
                        mHandler.obtainMessage(EVENT_LIST_CURRENT_NOS), 50);
                break;
            case R.id.btnListNotify:
                listCurrentNotification();
                break;
            case R.id.btnEnableUnEnableNotify:
                openNotificationAccess();
                break;
            default:
                break;
        }
    }
    // ...... 其餘省略
}

功能分析 4:使用過程中的四大坑

細心的同學會發現代碼裡用了 Handler,還有一些奇怪但被註釋掉的代碼(比如 a.equals("b"))。這些都是踩坑留下的痕跡。

① 為什麼 onCreate 中要用 Handler 調 getActiveNotifications()

直接在 onCreate() 或 onBind() 中調用 getActiveNotifications(),拿不到任何數據。原因是 NotificationMonitor 此時尚未完成初始化,根子上是 INotificationListenerWrapper 對象 mWrapper 還沒被創建。看源碼就很清楚:

public StatusBarNotification[] getActiveNotifications() {
    try {
        return getNotificationInterface().getActiveNotificationsFromListener(mWrapper);
    } catch (android.os.RemoteException ex) {
        Log.v(TAG, "Unable to contact notification manager", ex);
    }
    return null;
}

它依賴 mWrapper,而 mWrapper 是在 onBind() 裡才初始化的。所以只要在 onBind() 完成之後再調用就能正常返回。這裡用 Handler 丟到後面的消息隊列,本質就是「延後執行」;為更保險,還可以用 sendEmptyMessageDelayed 加一點延時。

② NotificationMonitor 若在 onCreate 或 onBind 中 crash,該 service 就永久失效

這是最難纏的一個坑:一旦 onCreate() 或 onBind() 中拋出異常導致崩潰,即使你隨後修好了代碼並重新安裝,也必須重啟手機才能恢復——否則永遠收不到通知回調,onNotificationPosted 與 onNotificationRemoved 都不會被觸發。

代碼中故意註釋掉的 a.equals("b") 就是為了復現這個問題:去掉註釋會導致空指針異常、Demo 停止;此時把註釋加回去重新運行,程序能正常啟動,但監聽功能已經徹底失效。這涉及系統對已綁定 listener 的狀態緩存,後文分析原理時會再展開。

③ MainActivity 的 onClick 中為何要用 Handler 延遲

點擊刪除通知後,系統的通知狀態並不是同步更新的,此時 NotificationMonitor 的回調還沒被觸發,直接讀取拿到的仍是上一次的舊數據。加一個 50ms 延遲,等系統完成回調之後再刷新界面,數據就正確了。而 50ms 在用戶感知層面幾乎不存在。

④ 為什麼要用 ArrayList 保存 StatusBarNotification 數組

getActiveNotifications() 返回的是 StatusBarNotification[],長度會隨通知增減而變化,用普通字段存儲無法跟進更新。把它包進 ArrayList,每次回調時用 set(0, array) 整體替換,既簡便又能保證始終只有一份有效數據。

總結

NotificationListenerService 是 Android 4.3 之後新增的接口服務,讓三方應用第一次能夠合法地獲取系統通知信息;4.4 加入的 Notification.extras 進一步豐富了可取內容。這些接口的開放極大便利了智能手錶配套、來電識別、通知管理等類型的應用,但也伴隨着明顯的隱私問題——用戶一旦授權,該應用就能讀到他所有的通知內容,包括驗證碼、聊天預覽。這也是後續版本不斷收緊相關審核策略的原因。

本文針對使用層面做了較為細緻的梳理,其中難免有失偏頗之處,本着互聯網知識共享的精神記錄出來:一是做筆記,二是希望給同樣在摸索的同學一些幫助。

後續會對 NotificationListenerService 的實現原理做進一步分析,敬請期待。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved