下面列出了怎么用com.google.zxing.Result的API类实例代码及写法,或者点击链接到github查看源代码。
private static Result[] decode(BinaryBitmap image, Map<DecodeHintType, ?> hints, boolean multiple)
throws NotFoundException, FormatException, ChecksumException {
List<Result> results = new ArrayList<>();
PDF417DetectorResult detectorResult = Detector.detect(image, hints, multiple);
for (ResultPoint[] points : detectorResult.getPoints()) {
DecoderResult decoderResult = PDF417ScanningDecoder.decode(detectorResult.getBits(), points[4], points[5],
points[6], points[7], getMinCodewordWidth(points), getMaxCodewordWidth(points));
Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.PDF_417);
result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, decoderResult.getECLevel());
PDF417ResultMetadata pdf417ResultMetadata = (PDF417ResultMetadata) decoderResult.getOther();
if (pdf417ResultMetadata != null) {
result.putMetadata(ResultMetadataType.PDF417_EXTRA_METADATA, pdf417ResultMetadata);
}
results.add(result);
}
return results.toArray(new Result[results.size()]);
}
ParcelableResultDecorator(Parcel in) {
try {
int numBits = in.readInt();
long timestamp = in.readLong();
String text = in.readString();
BarcodeFormat barcodeFormat = BarcodeFormat.values()[in.readInt()];
byte[] rawBytes = new byte[in.readInt()];
in.readByteArray(rawBytes);
ResultPoint[] resultPoints = new ResultPoint[in.readInt()];
for(int i = 0; i < resultPoints.length; i++) {
resultPoints[i] = new ResultPoint(in.readFloat(), in.readFloat());
}
this.result = new Result(text, rawBytes, numBits, resultPoints, barcodeFormat, timestamp);
} catch (Exception e) {
// result will be null if reading fails
}
}
private static Result translateResultPoints(Result result, int xOffset, int yOffset) {
ResultPoint[] oldResultPoints = result.getResultPoints();
if (oldResultPoints == null) {
return result;
}
ResultPoint[] newResultPoints = new ResultPoint[oldResultPoints.length];
for (int i = 0; i < oldResultPoints.length; i++) {
ResultPoint oldPoint = oldResultPoints[i];
if (oldPoint != null) {
newResultPoints[i] = new ResultPoint(oldPoint.getX() + xOffset, oldPoint.getY() + yOffset);
}
}
Result newResult = new Result(result.getText(),
result.getRawBytes(),
result.getNumBits(),
newResultPoints,
result.getBarcodeFormat(),
result.getTimestamp());
newResult.putAllMetadata(result.getResultMetadata());
return newResult;
}
public List<HistoryItem> buildHistoryItems() {
SQLiteOpenHelper helper = new DBHelper(activity);
List<HistoryItem> items = new ArrayList<HistoryItem>();
SQLiteDatabase db = null;
Cursor cursor = null;
try {
db = helper.getReadableDatabase();
cursor = db.query(DBHelper.TABLE_NAME, COLUMNS, null, null, null, null, DBHelper.TIMESTAMP_COL + " DESC");
while (cursor.moveToNext()) {
String text = cursor.getString(0);
String display = cursor.getString(1);
String format = cursor.getString(2);
long timestamp = cursor.getLong(3);
String details = cursor.getString(4);
Result result = new Result(text, null, null, BarcodeFormat.valueOf(format), timestamp);
items.add(new HistoryItem(result, display, details));
}
} finally {
close(cursor, db);
}
return items;
}
@Override
public Result decodeRow(int rowNumber,
BitArray row,
Map<DecodeHintType,?> hints) throws NotFoundException {
Pair leftPair = decodePair(row, false, rowNumber, hints);
addOrTally(possibleLeftPairs, leftPair);
row.reverse();
Pair rightPair = decodePair(row, true, rowNumber, hints);
addOrTally(possibleRightPairs, rightPair);
row.reverse();
for (Pair left : possibleLeftPairs) {
if (left.getCount() > 1) {
for (Pair right : possibleRightPairs) {
if (right.getCount() > 1 && checkChecksum(left, right)) {
return constructResult(left, right);
}
}
}
}
throw NotFoundException.getNotFoundInstance();
}
/**
* Handler scan result
*
* @param result
* @param barcode
*/
public void handleDecode(Result result, Bitmap barcode) {
inactivityTimer.onActivity();
playBeepSoundAndVibrate();
String resultString = result.getText();
if (TextUtils.isEmpty(resultString)) {
Toast.makeText(CaptureActivity.this, "Scan failed!", Toast.LENGTH_SHORT).show();
} else {
Intent resultIntent = new Intent();
Bundle bundle = new Bundle();
bundle.putString(INTENT_EXTRA_KEY_QR_SCAN, resultString);
resultIntent.putExtras(bundle);
this.setResult(RESULT_OK, resultIntent);
}
CaptureActivity.this.finish();
}
private void decode(final byte[] data) {
final PlanarYUVLuminanceSource source = cameraManager.buildLuminanceSource(data);
final BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
hints.put(DecodeHintType.NEED_RESULT_POINT_CALLBACK, (ResultPointCallback) dot -> runOnUiThread(() -> scannerView.addDot(dot)));
final Result scanResult = reader.decode(bitmap, hints);
runOnUiThread(() -> handleResult(scanResult));
} catch (final ReaderException x) {
// retry
cameraHandler.post(fetchAndDecodeRunnable);
} finally {
reader.reset();
}
}
@Override
public void handleResult(Result result) {
// Received Barcode Result!
WritableMap event = Arguments.createMap();
event.putString("data", result.getText());
event.putString("type", result.getBarcodeFormat().toString());
ReactContext reactContext = (ReactContext)getContext();
reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
getId(),
"topChange",
event);
startCamera(mCameraId);
setFlash(torchModeIsEnabled());
}
@Override
public void handleMessage(Message message) {
if (message.what == R.id.restart_preview) {
restartPreviewAndDecode();
} else if (message.what == R.id.decode_succeeded) { // 解析成功
DevLogger.dTag(TAG, "解析成功");
mState = State.SUCCESS;
Bundle bundle = message.getData();
mDecodeResult.handleDecode((Result) message.obj, bundle);
} else if (message.what == R.id.decode_failed) { // 解析失败 ( 解析不出来触发 )
DevLogger.dTag(TAG, "解析失败");
// 表示预览中
mState = State.PREVIEW;
// 设置预览解码线程
requestPreviewFrame(mDecodeThread.getHandler(), R.id.decode);
}
}
/**
* A valid barcode has been found, so give an indication of success and show
* the results.
*
* @param rawResult
* The contents of the barcode.
*
* @param bundle
* The extras
*/
public void handleDecode(Result rawResult, Bundle bundle) {
String text = rawResult.getText();
Log.i("test", text);
if (text.contains("product_key=") & text.contains("did=")
&& text.contains("passcode=")) {
inactivityTimer.onActivity();
product_key = getParamFomeUrl(text, "product_key");
did = getParamFomeUrl(text, "did");
passcode = getParamFomeUrl(text, "passcode");
Log.i("passcode product_key did", passcode + " " + product_key
+ " " + did);
ToastUtils.showShort(this, "扫码成功");
mHandler.sendEmptyMessage(handler_key.START_BIND.ordinal());
} else {
handler = new CaptureActivityHandler(this, cameraManager,
DecodeThread.ALL_MODE);
}
}
@Override
public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints)
throws NotFoundException, ChecksumException, FormatException {
DecoderResult decoderResult;
ResultPoint[] points;
if (hints != null && hints.containsKey(DecodeHintType.PURE_BARCODE)) {
BitMatrix bits = extractPureBits(image.getBlackMatrix());
decoderResult = decoder.decode(bits, hints);
points = NO_POINTS;
} else {
DetectorResult detectorResult = new Detector(image.getBlackMatrix()).detect(hints);
decoderResult = decoder.decode(detectorResult.getBits(), hints);
points = detectorResult.getPoints();
}
Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.QR_CODE);
List<byte[]> byteSegments = decoderResult.getByteSegments();
if (byteSegments != null) {
result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
}
String ecLevel = decoderResult.getECLevel();
if (ecLevel != null) {
result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
}
return result;
}
/**
* 从相册返回扫描结果
*
* @param uri 图片地址
*/
private void operateAlbumScanResult(Uri uri) {
int myWidth = getResources().getDisplayMetrics().widthPixels;
int myHeight = getResources().getDisplayMetrics().heightPixels;
Glide.with(CaptureActivity.this)
.load(uri)
.asBitmap()
.into(new SimpleTarget<Bitmap>(myWidth, myHeight) {
@Override
public void onResourceReady(Bitmap resource,
GlideAnimation<? super Bitmap> glideAnimation) {
Result resultZxing = new DecodeUtils(DecodeUtils.DECODE_DATA_MODE_ALL)
.decodeWithZxing(resource);
Log.i(TAG, "resultZxing >> " + resultZxing);
if (resultZxing != null) {
handleDecode(resultZxing, null);
} else {
SystemUtils.showHandlerToast(CaptureActivity.this,
"未发现二维码/条形码");
}
}
});
}
public String decodeWithZxing(byte[] data, int width, int height, Rect crop) {
MultiFormatReader multiFormatReader = new MultiFormatReader();
multiFormatReader.setHints(changeZXingDecodeDataMode());
Result rawResult = null;
PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(data, width, height,
crop.left, crop.top, crop.width(), crop.height(), false);
if (source != null) {
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
rawResult = multiFormatReader.decodeWithState(bitmap);
} catch (ReaderException re) {
// continue
} finally {
multiFormatReader.reset();
}
}
return rawResult != null ? rawResult.getText() : null;
}
@Override
public void handleMessage(Message message) {
if (message.what == R.id.restart_preview) {
restartPreviewAndDecode();
} else if (message.what == R.id.decode_succeeded) {
state = State.SUCCESS;
Bundle bundle = message.getData();
activity.handleDecode((Result) message.obj, bundle);
} else if (message.what == R.id.decode_failed) {// We're decoding as fast as possible, so when one
// decode fails,
// start another.
state = State.PREVIEW;
cameraManager.requestPreviewFrame(decodeThread.getHandler(), R.id.decode);
} else if (message.what == R.id.return_scan_result) {
activity.setResult(Activity.RESULT_OK, (Intent) message.obj);
activity.finish();
}
}
@Override
public WifiParsedResult parse(Result result) {
String rawText = getMassagedText(result);
if (!rawText.startsWith("WIFI:")) {
return null;
}
String ssid = matchSinglePrefixedField("S:", rawText, ';', false);
if (ssid == null || ssid.length() == 0) {
return null;
}
String pass = matchSinglePrefixedField("P:", rawText, ';', false);
String type = matchSinglePrefixedField("T:", rawText, ';', false);
if (type == null) {
type = "nopass";
}
boolean hidden = Boolean.parseBoolean(matchSinglePrefixedField("B:", rawText, ';', false));
return new WifiParsedResult(type, ssid, pass, hidden);
}
/**
* Handler scan result
*
* @param result
* @param barcode
*/
public void handleDecode(Result result, Bitmap barcode) {
inactivityTimer.onActivity();
playBeepSoundAndVibrate();
String resultString = result.getText();
handleResult(resultString);
}
@Override
public void handleMessage(Message message) {
int id = message.what;
if (id == R.id.auto_focus) {
//Log.d(TAG, "Got auto-focus message");
// When one auto focus pass finishes, start another. This is the closest thing to
// continuous AF. It does seem to hunt a bit, but I'm not sure what else to do.
if (state == State.PREVIEW) {
CameraManager.get().requestAutoFocus(this, R.id.auto_focus);
}
} else if (id == R.id.restart_preview) {
Log.d(TAG, "Got restart preview message");
restartPreviewAndDecode();
} else if (id == R.id.decode_succeeded) {
Log.d(TAG, "Got decode succeeded message");
state = State.SUCCESS;
Bundle bundle = message.getData();
/***********************************************************************/
Bitmap barcode = bundle == null ? null :
(Bitmap) bundle.getParcelable(DecodeThread.BARCODE_BITMAP);//���ñ����߳�
activity.handleDecode((Result) message.obj, barcode);//���ؽ��
/***********************************************************************/
} else if (id == R.id.decode_failed) {
// We're decoding as fast as possible, so when one decode fails, start another.
state = State.PREVIEW;
CameraManager.get().requestPreviewFrame(decodeThread.getHandler(), R.id.decode);
} else if (id == R.id.return_scan_result) {
Log.d(TAG, "Got return scan result message");
activity.setResult(Activity.RESULT_OK, (Intent) message.obj);
activity.finish();
} else if (id == R.id.launch_product_query) {
Log.d(TAG, "Got product query message");
String url = (String) message.obj;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
activity.startActivity(intent);
}
}
@Override
public void handleResult(Result result) {
Intent data = new Intent();
data.setData(Uri.parse(result.getText()));
setResult(RESULT_OK, data);
finish();
}
@Override
public Result[] decodeMultiple(BinaryBitmap image, Map<DecodeHintType,?> hints)
throws NotFoundException {
List<Result> results = new ArrayList<>();
doDecodeMultiple(image, hints, results, 0, 0, 0);
if (results.isEmpty()) {
throw NotFoundException.getNotFoundInstance();
}
return results.toArray(new Result[results.size()]);
}
private static Result maybeReturnResult(Result result) throws FormatException {
String text = result.getText();
if (text.charAt(0) == '0') {
return new Result(text.substring(1), null, result.getResultPoints(), BarcodeFormat.UPC_A);
} else {
throw FormatException.getFormatInstance();
}
}
public ProductParsedResult parse(Result result)
{
BarcodeFormat barcodeformat = result.getBarcodeFormat();
if (barcodeformat == BarcodeFormat.UPC_A || barcodeformat == BarcodeFormat.UPC_E || barcodeformat == BarcodeFormat.EAN_8 || barcodeformat == BarcodeFormat.EAN_13) goto _L2; else goto _L1
_L1:
return null;
_L2:
String s;
s = result.getText();
int i = s.length();
int j = 0;
label0:
do
{
label1:
{
if (j >= i)
{
break label1;
}
char c = s.charAt(j);
if (c < '0' || c > '9')
{
break label0;
}
j++;
}
} while (true);
if (true) goto _L1; else goto _L3
_L3:
String s1;
if (barcodeformat == BarcodeFormat.UPC_E)
{
s1 = UPCEReader.convertUPCEtoUPCA(s);
} else
{
s1 = s;
}
return new ProductParsedResult(s, s1);
}
private static Result maybeReturnResult(Result result) throws FormatException {
String text = result.getText();
if (text.charAt(0) == '0') {
Result retval = new Result(text.substring(1), null, result.getResultPoints(), BarcodeFormat.UPC_A);
retval.putAllMetadata(result.getResultMetadata());
return retval;
} else {
throw FormatException.getFormatInstance();
}
}
public EmailAddressParsedResult parse(Result result)
{
String s = result.getText();
String as[];
String s1;
if (s.startsWith("MATMSG:"))
{
if ((as = a("TO:", s, true)) != null && a(s1 = as[0]))
{
return new EmailAddressParsedResult(s1, b("SUB:", s, false), b("BODY:", s, false), (new StringBuilder()).append("mailto:").append(s1).toString());
}
}
return null;
}
@Override
public void handleResult(Result result) {
QRCode qrCode = new QRCode();
try {
JSONObject json = new JSONObject(String.valueOf(result));
qrCode.setAddress(json.getString("address"));
qrCode.setAmount(json.getString("amount"));
qrCode.setMessage(json.getString("message"));
qrCode.setTag(json.getString("tag"));
} catch (JSONException e) {
e.printStackTrace();
}
//remove all fragment from backStack, right, 2 times
getActivity().onBackPressed();
getActivity().onBackPressed();
Bundle bundle = new Bundle();
bundle.putParcelable(Constants.QRCODE, qrCode);
Fragment fragment = new NewTransferFragment();
fragment.setArguments(bundle);
getActivity().getFragmentManager().beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.replace(R.id.container, fragment, null)
.addToBackStack(null)
.commit();
}
@Override
public URIParsedResult parse(Result result) {
String rawText = getMassagedText(result);
// We specifically handle the odd "URL" scheme here for simplicity and
// add "URI" for fun
// Assume anything starting this way really means to be a URI
if (rawText.startsWith("URL:") || rawText.startsWith("URI:")) {
return new URIParsedResult(rawText.substring(4).trim(), null);
}
rawText = rawText.trim();
return isBasicallyValidURI(rawText) ? new URIParsedResult(rawText, null) : null;
}
@Override
public Result[] decodeMultiple(BinaryBitmap image, Map<DecodeHintType,?> hints)
throws NotFoundException {
List<Result> results = new ArrayList<>();
doDecodeMultiple(image, hints, results, 0, 0, 0);
if (results.isEmpty()) {
throw NotFoundException.getNotFoundInstance();
}
return results.toArray(new Result[results.size()]);
}
@Override
public Result[] decodeMultiple(BinaryBitmap image, Map<DecodeHintType,?> hints)
throws NotFoundException {
List<Result> results = new ArrayList<>();
doDecodeMultiple(image, hints, results, 0, 0, 0);
if (results.isEmpty()) {
throw NotFoundException.getNotFoundInstance();
}
return results.toArray(new Result[results.size()]);
}
private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) {
// Bitmap isn't used yet -- will be used soon
if (handler == null) {
savedResultToShow = result;
} else {
if (result != null) {
savedResultToShow = result;
}
if (savedResultToShow != null) {
Message message = Message.obtain(handler, R.id.decode_succeeded, savedResultToShow);
handler.sendMessage(message);
}
savedResultToShow = null;
}
}
String buildReplyURL(Result rawResult, ResultHandler resultHandler) {
String result = returnUrlTemplate;
result = replace(CODE_PLACEHOLDER,
returnRaw ? rawResult.getText() : resultHandler.getDisplayContents(), result);
result = replace(RAW_CODE_PLACEHOLDER, rawResult.getText(), result);
result = replace(FORMAT_PLACEHOLDER, rawResult.getBarcodeFormat().toString(), result);
result = replace(TYPE_PLACEHOLDER, resultHandler.getType().toString(), result);
result = replace(META_PLACEHOLDER, String.valueOf(rawResult.getResultMetadata()), result);
return result;
}
ResultHandler(Activity activity, ParsedResult result, Result rawResult) {
this.result = result;
this.activity = activity;
this.rawResult = rawResult;
this.customProductSearch = parseCustomSearchURL();
fakeR = new FakeR(activity);
// Make sure the Shopper button is hidden by default. Without this, scanning a product followed
// by a QR Code would leave the button on screen among the QR Code actions.
View shopperButton = activity.findViewById(fakeR.getId("id", "shopper_button"));
shopperButton.setVisibility(View.GONE);
}