Android NotificationListenerService: how to know i

2019-07-09 13:50发布

I'm working with notifications generated by every app (not only mine) on my Android device (android 5.1.1). By extending NotificationListenerService I'm able to know when a push notification is posted (overriding the "onNotificationPosted" method) and when a notification is removed (overriding the "onNotificationRemoved" method).

The problem is that I would like to know how the notification was removed: a) by clicking it (so opening the app) or b) by swyping it (so it is only removed) ?

Is it possible to know it? Thank you in advance!

1条回答
聊天终结者
2楼-- · 2019-07-09 14:41

The best way to do it is to get the list of all running processes! So, in the onNotificationRemoved method we can: 1. obtain the list of running processes using the Android Processes library 2. compare each process name with the packageName 3. if the comparison return a true value, we check if the process is in foreground

public void onNotificationRemoved(StatusBarNotification sbn) {
    String packageName = sbn.getPackageName();
    try {
        List<AndroidAppProcess> processes = ProcessManager.getRunningAppProcesses();
        if (processes != null) {
            for (AndroidAppProcess process : processes) {
                String processName = process.name;
                if (processName.equals(packageName)) {
                    if (process.foreground ==true)
                    {
                        //user clicked on notification
                    }
                    else
                    {
                        //user swipe notification
                    }
                }
            }
        }
    }
    catch (Exception e)
    {
        String error = e.toString();
    }
}
查看更多
登录 后发表回答