ionic capacitor handling event from Android Java code

Viewed 1206

I'm using ionic-react and capacitor. I need to trigger an event from the Android native code and handle it from JavaScript. Here is my test code:

In MainActivity.java:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Initializes the Bridge
    this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
      // Additional plugins you've installed go here
      // Ex: add(TotallyAwesomePlugin.class);
    }});
    new Handler().postDelayed(new Runnable() {
      @Override
      public void run() {
        bridge.triggerWindowJSEvent("MyPushEvent", "test");
      }
    }, 25000);
  }

In App.tsx

window.addEventListener("MyPushEvent", function (msg) {
    console.log("Push Event: " + msg);
    alert("Window Push Event: " + msg);
  });

Basically, I'm calling bridge.triggerWindowJSEvent in onCreate after a long delay, making sure the event handler on the client has been added. However, nothing happens on the client side.

Please help!

2 Answers

I think it will not be done in this way, since the point in ionic apps is to start first the main activity which is main activity and after main activity lunches it starts to launch of method to launch index.html so all app pages will be launched within the main activity. What i've done before to achieve it was to make 2 handlers, the first is post delayed for 1500 ms which inside it will be the launching of index.html and the other handler uses method post instead of postdelayed since post will be added to queque of the hanlder thus will be added to the first post delayed handler so after the app launches after 2500 ms then app.tsx or app.ts in cordova will be launched and thus ready to recieve an event so after these 2500 ms we add a handler.post(..runnable ... and inside it launch you event and recieve it in app.tsx .

According to documentation: data must be a serialized JSON string value. The code below worked for me.

public void onResume(){
    super.onResume();

    new Handler().postDelayed(new Runnable() {
      @Override
      public void run() {
        bridge.triggerWindowJSEvent("MyPushEvent", "{\"test1\":\"test2\"}");
      }
    }, 5000);
  }

window.addEventListener('MyPushEvent', function (msg: any) {
    alert('Window Push Event: ' + msg.test1);
  });
Related