REG1
REG1

Reputation: 486

Cannot instantiate the type NotificationListenerService in Android

I am trying to access the getActiveNotifications() from the NotificationListenerService class, however it doesn't work, I have tried these to ways:

1)

    NotificationListenerService nls = new NotificationListenerService();
    activeNotifications = nls.getActiveNotifications();

2)

    activeNotifications = NotificationListener.class.getActiveNotifications();

But for 1) I get this error:

Cannot instantiate the type NotificationListenerService

and for 2) I get this error:

The method getActiveNotifications() is undefined for the type Class<NotificationListenerService>

This seems to be simple Java but I can't get it to work, what am I doing wrong? Any help is much appreciated, thanks.

Upvotes: 0

Views: 1003

Answers (1)

Simon Marquis
Simon Marquis

Reputation: 7526

To use NotificationListenerService, you need to create a custom class that extends from NotificationListenerService.
You can't instatiate it, the System will do it for you.

Add this to your AndroidManifest.xml:

    <service android:name="your.package.name.MyNLS"
        android:debuggable="true"
        android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" >
        <intent-filter>
            <action android:name="android.service.notification.NotificationListenerService" />
        </intent-filter>
    </service>

Create a NotificationListenerService class:

public class MyNLS extends NotificationListenerService {

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {

    }

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {

    }

}

Use this code to send the user to the Notification Listener Settings:

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

Then, inside your service you can call this to have the list of Active notifications:

for (StatusBarNotification sbn : getActiveNotifications()) {
    /// do something
}

Upvotes: 4

Related Questions