java 使用zxing扫描意图传递额外数据

agxfikkp  于 2022-10-29  发布在  Java
关注(0)|答案(1)|浏览(124)

我正在使用https://github.com/zxing集成一个条形码扫描仪。我想传递一些额外的数据-uuid下面-沿着条形码。
下面的uuid1uuid2都得到null。我遗漏了什么?

public void startScanner(String uuid){
    IntentIntegrator integrator = new IntentIntegrator(this);

    integrator.setDesiredBarcodeFormats(IntentIntegrator.PRODUCT_CODE_TYPES);
    integrator.setPrompt("");
    integrator.setCameraId(0);
    integrator.setBeepEnabled(false);

    Intent intent = integrator.createScanIntent();
    intent.putExtra("uuid", uuid);

    startActivityForResult(intent, IntentIntegrator.REQUEST_CODE);
}

public void onActivityResult(int requestCode, int resultCode, Intent intent) 
{
    IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
    if (scanResult != null) {
        String code = scanResult.getContents();
        JSONObject json = new JSONObject();
        try {
            String uuid1 = intent.getStringExtra("uuid");
            String uuid2 = intent.getExtras().getString("uuid");

            json.put("uuid", uuid1);
            json.put("barCode", code);
            this.webViewManager.runScript("startScannerCallback", json);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
xoefb8l8

xoefb8l81#

reddit上的某个人告诉我创建一个自定义协定。这样就成功了(但不是线程安全的!):

public class ScanContract extends com.journeyapps.barcodescanner.ScanContract {

    private String scope;

    public void setScope(String scope) {
        this.scope = scope;
    }

    @Override
    public ScanIntentResult parseResult(int resultCode, @Nullable Intent intent) {
        ScanIntentResult scanIntentResult = super.parseResult(resultCode, intent);
        scanIntentResult.getOriginalIntent().putExtra("foo", scope);
        scope = null;
        return scanIntentResult;
    }
}

发射呼叫:

((ScanContract)barcodeLauncher.getContract()).setScope("bar");

接收范围:

String foo = result.getOriginalIntent().getStringExtra("foo");

当然,这只有在您不同时启动Activity多次的情况下才有效,因为Contract对象只被示例化一次!
哦,而且我正在使用新的API来获取活动结果:)

相关问题