gpt4 book ai didi

java - 在 BroadcastReceiver 中使用 callbackContext

转载 作者:行者123 更新时间:2023-11-29 04:43:01 27 4
gpt4 key购买 nike

我有一个使用名为“com.hyipc.core.service.barcode.BarcodeService2D”的服务扫描条形码的 Cordova 插件。这是通过向广播接收器注册接收器来完成的。

扫描过程运行成功,但我想将扫描结果发送回我的 cordova 应用程序,我看到这是使用 callbackContext.success(strBarcode) 完成的。问题是我不能在我的 BarcodeReceiverClass 中使用它。有什么方法可以将数据从 onReceive 内部发送回我的应用程序?

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);
}
}
}
}

最佳答案

您需要将回调上下文参数传递给您的 BarcodeReceiver 类:

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);
}
}
}

关于java - 在 BroadcastReceiver 中使用 callbackContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38391275/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com