问题
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:
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();
}
}
来源:https://stackoverflow.com/questions/33088355/android-notificationlistenerservice-how-to-know-if-user-clicked-on-the-notifica