This example aims to teach you how to intercept notifications received by the Android System.
All the gradle files have been updated to the latest version available because people were having trouble getting it to compile. Some libraries were deprecated, so I updated them to the new ones, and the Android target version is now set to Android 10 instead of Android 5.
TLDR; It's still working!!
https://developer.android.com/guide/topics/ui/notifiers/notifications.html
As stated in the official Google Android Website, a notification is a message that can be displayed outside of the application normal User Interface
It should look similar to this:
In order to intercept a notification received by the android system we need to have a specific service running on the system's background. This service is called: NotificationListenerService.
What the service basically does is: It registers itseft to the android system and after that starts to listen to the calls from the system when new notifications are posted or removed, or their ranking changed.
When the NotificationListenerService identifies that a notification has been posted, removed or had its ranking modified it does what you told it to.
1. Declare the Service in your AndroidManifest.xml file with the BIND_NOTIFICATION_LISTENER_SERVICE
permission and include an intent filter with the SERVICE_INTERFACE action
.
Like this:
<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>
2. Extend the NotificationListenerService class and implement at least the following methods:
public class NotificationListenerExampleService extends NotificationListenerService {
@Override
public IBinder onBind(Intent intent) {
return super.onBind(intent);
}
@Override
public void onNotificationPosted(StatusBarNotification sbn){
// Implement what you want here
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn){
// Implement what you want here
}
}
To illustrate the interception of notifications I've built a NotificationListenerService that does the following:
It changes the ImageView present on the screen whenever it receives a notification from the following apps:
- 2016 on a ZenPhone2 (Android Lollipop 5.0)
- 2021 on a Samsung Galaxy S7 (Android Oreo 8.0.0)