将扫描结果传递给其他意图

时间:2019-05-02 19:43:48

标签: java android zxing

我从扫描片段中获得了扫描结果,但是如何将结果发送到其他目的?

在我的扫描片段中

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(result != null) {
            Intent intent1 = new Intent(getActivity(), Trial.class);
            intent1.putExtra("Barcodes", "hi");
            startActivity(intent1);
        }
    }

1 个答案:

答案 0 :(得分:0)

问题:IntentResult是最终类,并且没有实现Parcelable接口,因此您无法使用Intent.putExtra()将其发送到另一个活动。

解决方案::创建自己的ScanResult类,它是IntentResult的克隆版本。

ScanResult.java

public class ScanResult implements Parcelable {

    public String contents;
    public String formatName;
    public byte[] rawBytes;
    public Integer orientation;
    public String errorCorrectionLevel;

    public ScanResult(IntentResult intentResult) {
        contents = intentResult.getContents();
        formatName = intentResult.getFormatName();
        rawBytes = intentResult.getRawBytes();
        orientation = intentResult.getOrientation();
        errorCorrectionLevel = intentResult.getErrorCorrectionLevel();
    }

    protected ScanResult(Parcel in) {
        contents = in.readString();
        formatName = in.readString();
        rawBytes = in.createByteArray();
        long orientationInLong = in.readLong();
        orientation = orientationInLong != Long.MAX_VALUE ? (int) orientationInLong : null;
        errorCorrectionLevel = in.readString();
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(contents);
        dest.writeString(formatName);
        dest.writeByteArray(rawBytes);
        dest.writeLong(orientation != null ? orientation : Long.MAX_VALUE);
        dest.writeString(errorCorrectionLevel);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public static final Creator<ScanResult> CREATOR = new Creator<ScanResult>() {
        @Override
        public ScanResult createFromParcel(Parcel in) {
            return new ScanResult(in);
        }

        @Override
        public ScanResult[] newArray(int size) {
            return new ScanResult[size];
        }
    };
}

在片段中使用它。

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
    if(result != null) {
        ScanResult scanResult = new ScanResult(result);
        Intent intent1 = new Intent(getActivity(), Trial.class);
        intent1.putExtra("scanResult", scanResult);
        startActivity(intent1);
    }
}

在收到的活动中(Trial.java)

ScanResult scanResult = getIntent().getParcelableExtra<ScanResult>("scanResult");