Alexandru Pufan
Alexandru Pufan

Reputation: 1912

Use callbackContext inside BroadcastReceiver

I have a Cordova plugin which scans a barcode, using a service named "com.hyipc.core.service.barcode.BarcodeService2D". This is done by registering a receiver with Broadcast Receiver.

The scanning process runs successfully, but I want to send back to my cordova app the scanning result, which I saw is done using callbackContext.success(strBarcode). The problem is that I cannot use this inside my BarcodeReceiverClass. Is there any way I can send data from inside onReceive back to my app?

public class Scanner extends CordovaPlugin {

    private BroadcastReceiver mReceiver = new BarcodeReceiver();
    private Intent intentService = new Intent("com.hyipc.core.service.barcode.BarcodeService2D");
    public static final String ACTION_BARCODE_SERVICE_BROADCAST = "action_barcode_broadcast";
    public static final String KEY_BARCODE_STR = "key_barcode_string";
    private String strBarcode = "";

    @Override
    public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {

        if (action.equals("scan")) {
            scan();
            return true;
        } else {
            return false;
    }
}

    public void scan() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_BARCODE_SERVICE_BROADCAST);

        cordova.getActivity().startService(intentService);
        cordova.getActivity().registerReceiver(mReceiver, filter);  
    }

    public class BarcodeReceiver extends BroadcastReceiver {
        public void onReceive(Context ctx, Intent intent) {
            if (intent.getAction().equals(ACTION_BARCODE_SERVICE_BROADCAST)) {
                strBarcode = intent.getExtras().getString(KEY_BARCODE_STR);
                callbackContext.success(strBarcode);
            }
        }
    }
}

Upvotes: 2

Views: 1344

Answers (1)

Frix33
Frix33

Reputation: 1241

You need to pass the callback context parameter to you BarcodeReceiver class:

public class Scanner extends CordovaPlugin {
   ....
    private BroadcastReceiver mReceiver = null;

    @Override
    public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
       ....
       mReceiver = new BarcodeReceiver(callbackContext);
       ....
    }
   ....
}

public class BarcodeReceiver extends BroadcastReceiver {

    private CallbackContext callbackContext;

    public BarcodeReceiver (CallbackContext callbackContext) {
        this.callbackContext = callbackContext;
    }

    public void onReceive(Context ctx, Intent intent) {
        if (intent.getAction().equals(ACTION_BARCODE_SERVICE_BROADCAST)) {
            strBarcode = intent.getExtras().getString(KEY_BARCODE_STR);
            callbackContext.success(strBarcode);
        }
    }
} 

Upvotes: 4

Related Questions