Notification Listener Plugin for Android With Cordova

| Comments

When we were developing Watchduino2 we required to forward messages for all notifications we receive in our phone by using the NotificationListenerService available on Android.

We managed to do this in the first version of our companion app on native code, unfortunatelly, we realised this feature was not available yet on Cordova, the new framework we use for building our cool responsive companion app.

The solution? Roll our own Cordova plugin to provide this functionality!

How it works

The basic idea of this plugin is to create a callback from JavaScript that will be triggered everytime you get a notification on Android.

How to install

Installing this plugin is really simple, and it’s like installing any other plugin on Cordova.

cordova plugin add https://github.com/coconauts/NotificationListener-cordova

How to use

Simply create a listener from javascript using this method inside the Cordova initialization code.

notificationListener.listen(onNotification,onError);

Sample code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var app = {
    initialize: function() {
        this.bindEvents();
    },
    bindEvents: function() {
      document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    onDeviceReady: function() {
      log("Cordova start", "Device ready");

      notificationListener.listen(function(n){
          console.log("Received notification " + JSON.stringify(n) );
        }, function(e){
          console.log("Notification Error " + e);
        })
    }
};

app.initialize();

Disclaimer

As far as I know, listening for notifications is only supported by Android phones (from version 4.0), and we haven’t done any IOS development in the past, so I don’t thing is possible to port this plugin to IOS. But feel free to contribute to our project if you think it can be extended to other platforms.

Comments