【问题标题】:Android: pass data from initial activity (launching Zxing scanner) to onActivityResult callbackAndroid:将数据从初始活动(启动 Zxing 扫描仪)传递到 onActivityResult 回调
【发布时间】:2020-07-23 09:41:37
【问题描述】:

我在我的 Android 应用程序中使用了 zxing-android-embedded 库。在调用 initialScan() 方法从我的活动中启动扫描仪之前,我设置了一个类变量 scanedItemId 以了解我单击了哪个项目进行扫描:

[...]
scanedItemId = currentItem.id // The current item where we clicked on.
IntentIntegrator qrCodeScanner = new IntentIntegrator(MyActivity.this);
qrCodeScanner.setOrientationLocked(false);
qrCodeScanner.initiateScan();
[...]

然后我通过 onActivityResult 方法得到结果。它运行良好,但我的类变量 scanedItemId 为空,因为活动已重新启动。是否可以保留 MyActivity 的初始实例(已设置好 scanedItemId)或通过 IntentIntegrator 传递我需要的值以将其返回到 MyActivity 的新实例?

[...]
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case IntentIntegrator.REQUEST_CODE:
            // Here the scanedItemId is always null.
[...]

如果可能的话,我不想使用硬持久性(如 db 或文件)来获取我的 scanedItemId 值。

希望它足够清楚

【问题讨论】:

    标签: java android android-intent zxing onactivityresult


    【解决方案1】:

    您可以像这样添加更多自定义数据:

    scanedItemId = currentItem.id // The current item where we clicked on.
    IntentIntegrator qrCodeScanner = new IntentIntegrator(MyActivity.this);
    quCodeScanner.addExtra("ITEM_ID", scanedItemId);//add your data
    qrCodeScanner.setOrientationLocked(false);
    qrCodeScanner.initiateScan();
    

    因为您使用的库没有返回您的数据。您可以分叉该库并添加如下代码:

    在 CaptureManager 类中 编辑 initializeFromIntent 方法

    if (intent != null) {
        data = intent.getIntExtra("ITEM_ID", 0);//save your data
    }
    

    和resultIntent方法

    intent.putExtra("ITEM_ID", data);//return your data
    

    现在在 onActivityResult 你可以得到你的数据

    IntentResult result = IntentIntegrator.parseActivityResult(resultCode, data);
    if (result.getOriginalIntent().hasExtra("ITEM_ID")) {
        Toast.makeText(this,"Item Id : " + String.valueOf(result.getOriginalIntent().getIntExtra("ITEM_ID",0)), Toast.LENGTH_LONG).show();
    }
    

    【讨论】:

    • 好的,谢谢,但我无法从 onActivityResult 方法中获得额外的结果。我和这里有同样的问题:stackoverflow.com/questions/49309732/…
    • 好的,所以它确认按原样使用库,不可能通过其 Intent 传递数据。显然我更喜欢不分叉库(主要是出于维护原因)。所以要么我尝试使用一个类变量(它暂时不起作用,因为我的活动被杀死并重新实例化),或者我必须找到另一个图书馆。无论如何,感谢您的解释和您花费的时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多