'Call custom capacitor plugin from another class

In capacitor 3, I've build a minimal plugin in Android which can send events from the native Android to javascript, whenever something is happening, by listening for events in javascript.

It's working fine from within the class, i.e. overriding OnStart of the class. But when I want to call the class and notify listeners from another class, how do I call the plugin class without making a new instance, so that whoever is listening, can still get the event.

I tried implementing it as singleton, but it is not allowed, I get a error in javascript error handler when doing so, just when I start listening to events. Also I can't make it static.

So how do I call the plugin class without making a new instance?

The javascriptcode:

IonicNativePlugin.addListener('EVENT_LISTENER_NAME', (message) => {
      alert(message.message);
    }).catch((error) => {
      alert('Error in EventListener');
    });

The java MainActivity code:

public class MainActivity extends BridgeActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
            registerPlugin(IonicNativeLogisPlugin.class);
    }
}

The plugin java code:

@CapacitorPlugin(name = "IonicNativePlugin")
public class IonicNativePlugin extends Plugin {
  @PluginMethod
  public void NotifyListeners(PluginCall call){
    JSObject result = new JSObject();
    result.put("message", "Hello!");
    notifyListeners("EVENT_LISTENER_NAME", result);
  }

  public void TheMethodIWantToCall(){
    JSObject ret = new JSObject();
    ret.put("message", "Hello from LISTENER!!");
    notifyListeners("EVENT_LISTENER_NAME", ret);
  }
}

The class I like to call from:

public class NotificationServiceExtension implements OSRemoteNotificationReceivedHandler {

  @Override
  public void remoteNotificationReceived(Context context, OSNotificationReceivedEvent notificationReceivedEvent) {
    OSNotification notification = notificationReceivedEvent.getNotification();
    notificationReceivedEvent.complete(notification);
    <-- call should be here
  }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source