Heads up! This post was written 9 years ago. Some information might be outdated or may have changed since then.
To use it we need to implement 2 callback methods. Both of them have paramether named
sbn which is object of StatusBarNotification class. In this example I will show quickly how to listen notification events with just print them to console.logs
Let's start with creating new Java Class named
NotificationService.java with following content: package me.yuks.demo;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import android.support.v4.content.LocalBroadcastManager;
public class NotificationService extends NotificationListenerService {
Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
String pack = sbn.getPackageName();
String text = "";
String title = "";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
Bundle extras = extras = sbn.getNotification().extras;
text = extras.getCharSequence("android.text").toString();
title = extras.getString("android.title");
}
Log.i("Package",pack);
Log.i("Title",title);
Log.i("Text",text);
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i("Msg","Notification was removed");
}
} Also we need to update our
Manifest file to include this newly created service.
So basically that is :) Run and enjoy :) Note: User require to enable notification permission from "Settings > Security > Notification access".