How to notify listeners inside an Android service

I’m making a Capacitor plugin that will listen on every new notification posted. I’ve created a NotificationListener service which is working properly. However, I couldn’t find a way to send events back to the plugin.

NotifListenerPlugin.java

public static void sendNotify(StatusBarNotification n) {
        Log.i("Notification","Recieved Notify event");
        JSObject ret = new JSObject();
        Bundle extras = n.getNotification().extras;
        ret.put("title",getExtra(extras,"android.title"));
        ret.put("packageName",n.getPackageName());
        ret.put("text",getExtra(extras,"android.text"));
        ret.put("textLines",getExtraLines(extras,"android.textLines"));
        notifyListeners("notification", ret); // Where the issues caused.
    }

NotifListenerService.java

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        String pk = sbn.getPackageName();
        if(pk.equals("android") && ignorePkg(pk) && sbn.isOngoing()) return;
        Log.d(TAG, "Notification from " + sbn.getPackageName());
        NotifListenerPlugin.sendNotify(sbn); // Static function
    }

If I make my sendNotify static, notifyListeners will not be available. I try making sendNotify non-static and do something like

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
            ...
            NotifListenerPlugin notif = new NotifListenerPlugin();
            notif.sendNotify(sbn);
            ...
    }

It still doesn’t work anyway. How can I send events from my service back to the plugin?

I found triggerJSEvent but it seems like we can’t get the bridge if it isn’t inside the plugin itself.

Any help or suggestions are welcome.
Thank you.

Environment

  • Windows 10 - 32 Bit
  • Capacitor v3 (beta) - ^3.0.0-rc.0
  • Android SDK v29 with all settings from defaults
  • Ionic Framework - 5.5.4
  • Angular Core - 11.2.1

You can only notify from the Plugin class, you’ll have to create some listener in your service that your plugin hooks to, so that when the listener fires, the plugin forward it.

Check our Network plugin as an example

It has a NetworkStatusChangeListener
And the NetworkPlugin.java class sets it

and forward it

Thank you for your reply. I’ll try this soon.