Cordova Broadcaster plugin not sending intents to index.js

36 Views Asked by At

I'm working on a project where I'm using Cordova Broadcaster to send a action.USER_PRESENT intent from my myBroadcastReceiver.java file to my Index.js. I know that the intent gets received by the myBroadcastReceiver.java file from Android, but it's not sending to my index.js file.

This is myBroadcastReceiver.java code:


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.widget.Toast;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.util.Log;


public class myBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        LocalBroadcastManager.getInstance(context).sendBroadcastSync(intent);
    }

}

This is my index.js code:

window.broadcaster.addEventListener("android.intent.action.USER_PRESENT", function (e) {
         console.log("com.android.action.SEND_SCAN_RESULT registered");
    });

I'm currently using LocalBroadcastManager 1.0.0 but on Androidx.core version 1.10.1 with Android API-33.

Thoughts?

Thanks for any help!

1

There are 1 best solutions below

0
nicholas riyan On

It seems like you're trying to use Cordova Broadcaster to send an intent from your Java BroadcastReceiver to your JavaScript index.js. However, you're using LocalBroadcastManager to send the broadcast, which is meant for sending broadcasts within your app's components, and not across the Cordova native-to-web boundary.

To send an intent from Java to JavaScript in a Cordova plugin, you should use Cordova's plugin architecture. You'll need to modify your plugin's Java code to call the JavaScript callback when the intent is received. Here's a simplified example:

In your myBroadcastReceiver.java:

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

public class MyBroadcastReceiverPlugin extends CordovaPlugin {

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("sendBroadcast")) {
            // Handle the intent processing here
            
            // Send the intent to JavaScript
            webView.sendJavascript("cordova.fireDocumentEvent('userPresent');");
            return true;
        }
        return false;
    }
}

In your index.js:

document.addEventListener("userPresent", function (e) {
    console.log("User present event received in JavaScript");
});

This example demonstrates how to use Cordova's plugin mechanism to bridge the communication between your Java code and your JavaScript code. Make sure you adjust this code according to your plugin's structure and requirements.

Remember to handle plugin initialization and error cases properly in your Java code as well.