This example aims to teach you how to intercept notifications received by the Android System.
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: