Tutorial details

Android NotificationListenerService Example | App Code for Sale | Preview

Android NotificationListenerService Example | Android Tutorial

NotificationListenerService is introduced in Android 4.3 (API 18). It allows an application to receive information about notifications as it creates or removes.

Overview PAGE TOP

Introduction

NotificationListenerService is introduced in Android 4.3 (API 18). It allows an application to receive information about notifications as it creates or removes. NotificationListenerService class is derived from the Service class. It has two abstract methods namely 1. onNotificationPosted 2. onNotificationRemoved.

To use NotificationListenerService, we need to create a java file which extends NotificationListenerService and implement two callback methods. Both methods have a parameter named “sbn”, which is an object of StatusBarNotification class. StatusBarNotification provides necessary information about Notifications.

NotificationListenerService provides facility to fetch active notifications using getActiveNotifications and also provides a feature to remove notifications using cancelAllNotifications.

Useful Methods PAGE TOP

  1. NotificationListenerService<br>onNotificationPosted()<br>onNotificationRemoved()<br>cancelAllNotifications()<br>getActiveNotifications()
  2. StatusBarNotification<br>getId()<br>getNotification()<br>getPackageName()<br>getPostTime()<br>isClearable()<br>isOngoing()

Note: User require to enable notification permission from “Settings > Security > Notification access”.

Source Code of NotificationListenerService PAGE TOP

Worth to see the source code, If you hare curious. It has two java files and two AIDL files: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/service/notification

Example PAGE TOP

This is simple example of NotificationListenerService, It has simple UI contain three buttons and one textview.

  • Create Notification – It will create simple notification so that we can test onNotificationPosted event
  • Clear All Notification – It will create all notification in notificationbar
  • List of Notification – It will display notification list in textview
  • TextView – display notification events and list of notification.

This example has Activity, Service and BroadcastReceiver. BroadcastReceiver used for communication between activity and service. We can’t access cancelAllNotifications() and getActiveNotifications() methods from activity directly so I use BroadcastReceivers.

Screenshots PAGE TOP

Source Code PAGE TOP

1. MainActivity.java

package com.kpbird.nlsexample;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
    private TextView txtView;
    private NotificationReceiver nReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity<em>main);
        txtView = (TextView) findViewById(R.id.textView);
        nReceiver = new NotificationReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.kpbird.nlsexample.NOTIFICATION</em>LISTENER<em>EXAMPLE");
        registerReceiver(nReceiver,filter);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(nReceiver);
    }
    public void buttonClicked(View v){
        if(v.getId() == R.id.btnCreateNotify){
            NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION</em>SERVICE);
            NotificationCompat.Builder ncomp = new NotificationCompat.Builder(this);
            ncomp.setContentTitle("My Notification");
            ncomp.setContentText("Notification Listener Service Example");
            ncomp.setTicker("Notification Listener Service Example");
            ncomp.setSmallIcon(R.drawable.ic<em>launcher);
            ncomp.setAutoCancel(true);
            nManager.notify((int)System.currentTimeMillis(),ncomp.build());
        }
        else if(v.getId() == R.id.btnClearNotify){
            Intent i = new Intent("com.kpbird.nlsexample.NOTIFICATION</em>LISTENER<em>SERVICE</em>EXAMPLE");
            i.putExtra("command","clearall");
            sendBroadcast(i);
        }
        else if(v.getId() == R.id.btnListNotify){
            Intent i = new Intent("com.kpbird.nlsexample.NOTIFICATION<em>LISTENER</em>SERVICE<em>EXAMPLE");
            i.putExtra("command","list");
            sendBroadcast(i);
        }
    }
    class NotificationReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            String temp = intent.getStringExtra("notification</em>event") + "n" + txtView.getText();
            txtView.setText(temp);
        }
    }
}

2. NLService.java

package com.kpbird.nlsexample;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
public class NLService extends NotificationListenerService {
    private String TAG = this.getClass().getSimpleName();
    private NLServiceReceiver nlservicereciver;
    @Override
    public void onCreate() {
        super.onCreate();
        nlservicereciver = new NLServiceReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.kpbird.nlsexample.NOTIFICATION<em>LISTENER</em>SERVICE<em>EXAMPLE");
        registerReceiver(nlservicereciver,filter);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(nlservicereciver);
    }
    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        Log.i(TAG,"**********  onNotificationPosted");
        Log.i(TAG,"ID :" + sbn.getId() + "t" + sbn.getNotification().tickerText + "t" + sbn.getPackageName());
        Intent i = new  Intent("com.kpbird.nlsexample.NOTIFICATION</em>LISTENER<em>EXAMPLE");
        i.putExtra("notification</em>event","onNotificationPosted :" + sbn.getPackageName() + "n");
        sendBroadcast(i);
    }
    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        Log.i(TAG,"********** onNOtificationRemoved");
        Log.i(TAG,"ID :" + sbn.getId() + "t" + sbn.getNotification().tickerText +"t" + sbn.getPackageName());
        Intent i = new  Intent("com.kpbird.nlsexample.NOTIFICATION<em>LISTENER</em>EXAMPLE");
        i.putExtra("notification<em>event","onNotificationRemoved :" + sbn.getPackageName() + "n");
        sendBroadcast(i);
    }
    class NLServiceReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getStringExtra("command").equals("clearall")){
                    NLService.this.cancelAllNotifications();
            }
            else if(intent.getStringExtra("command").equals("list")){
                Intent i1 = new  Intent("com.kpbird.nlsexample.NOTIFICATION</em>LISTENER<em>EXAMPLE");
                i1.putExtra("notification</em>event","=====================");
                sendBroadcast(i1);
                int i=1;
                for (StatusBarNotification sbn : NLService.this.getActiveNotifications()) {
                    Intent i2 = new  Intent("com.kpbird.nlsexample.NOTIFICATION<em>LISTENER</em>EXAMPLE");
                    i2.putExtra("notification<em>event",i +" " + sbn.getPackageName() + "n");
                    sendBroadcast(i2);
                    i++;
                }
                Intent i3 = new  Intent("com.kpbird.nlsexample.NOTIFICATION</em>LISTENER<em>EXAMPLE");
                i3.putExtra("notification</em>event","===== Notification List ====");
                sendBroadcast(i3);
            }
        }
    }
}

3. activitymain.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout</em>width="match<em>parent"
    android:layout</em>height="match<em>parent"
    android:paddingLeft="@dimen/activity</em>horizontal<em>margin"
    android:paddingRight="@dimen/activity</em>horizontal<em>margin"
    android:paddingTop="@dimen/activity</em>vertical<em>margin"
    android:paddingBottom="@dimen/activity</em>vertical<em>margin"
    tools:context=".MainActivity">
    <Button
            android:layout</em>width="wrap<em>content"
            android:layout</em>height="wrap<em>content"
            android:text="Create Notification"
            android:id="@+id/btnCreateNotify"
            android:onClick="buttonClicked"
            android:layout</em>alignParentTop="true"
            android:layout<em>alignParentLeft="true"
            android:layout</em>alignParentRight="true"/>
    <Button
            android:layout<em>width="wrap</em>content"
            android:layout<em>height="wrap</em>content"
            android:text="Clear All Notification"
            android:id="@+id/btnClearNotify"
            android:onClick="buttonClicked"
            android:layout<em>below="@+id/btnCreateNotify"
            android:layout</em>alignLeft="@+id/btnCreateNotify"
            android:layout<em>alignRight="@+id/btnCreateNotify"/>
    <ScrollView android:layout</em>width="match<em>parent"
                android:layout</em>height="match<em>parent"
                android:layout</em>alignParentBottom="true"
                android:layout<em>alignRight="@+id/btnListNotify"
                android:layout</em>below="@+id/btnListNotify"
                android:layout<em>alignLeft="@+id/btnListNotify">
        <TextView
                android:layout</em>width="match<em>parent"
                android:layout</em>height="wrap<em>content"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="NotificationListenerService Example"
                android:id="@+id/textView"
                />
    </ScrollView>
    <Button
            android:layout</em>width="wrap<em>content"
            android:layout</em>height="wrap<em>content"
            android:text="List of Notification"
            android:id="@+id/btnListNotify"
            android:onClick="buttonClicked"
            android:layout</em>below="@+id/btnClearNotify"
            android:layout<em>alignLeft="@+id/btnClearNotify"
            android:layout</em>alignRight="@+id/btnClearNotify"/>
</RelativeLayout>


4. AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.kpbird.nlsexample"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="18"
        android:targetSdkVersion="18" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic<em>launcher"
        android:label="@string/app</em>name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.kpbird.nlsexample.MainActivity"
            android:label="@string/app<em>name"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="com.kpbird.nlsexample.NLService"
                 android:label="@string/app</em>name"
                 android:permission="android.permission.BIND<em>NOTIFICATION</em>LISTENER_SERVICE">
            <intent-filter>
                <action android:name="android.service.notification.NotificationListenerService" />
            </intent-filter>
        </service>
    </application>
</manifest>
    

User following code to open Notification Access setting screen PAGE TOP

Intent intent=new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);


Reference PAGE TOP

http://www.javacodegeeks.com/2013/10/android-notificationlistenerservice-example.html

0 Comments Leave a comment

Please login in order to leave a comment.

Newest first
!

Sign-in to your Chupamobile Account.

The Easiest way to Launch your next App or Game.

Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.