/** * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode. * * @param barcode A bitmap of the captured image. * @param scaleFactor amount by which thumbnail was scaled * @param rawResult The decoded results which contains the points to draw. */ private void drawResultPoints(Bitmap barcode, float scaleFactor, Result rawResult) { ResultPoint[] points = rawResult.getResultPoints(); if (points != null && points.length > 0) { Canvas canvas = new Canvas(barcode); Paint paint = new Paint(); paint.setColor(getResources().getColor(R.color.result_points)); if (points.length == 2) { paint.setStrokeWidth(4.0f); drawLine(canvas, paint, points[0], points[1], scaleFactor); } else if (points.length == 4 && (rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A || rawResult.getBarcodeFormat() == BarcodeFormat.EAN_13)) { // Hacky special case -- draw two lines, for the barcode and metadata drawLine(canvas, paint, points[0], points[1], scaleFactor); drawLine(canvas, paint, points[2], points[3], scaleFactor); } else { paint.setStrokeWidth(10.0f); for (ResultPoint point : points) { if (point != null) { canvas.drawPoint(scaleFactor * point.getX(), scaleFactor * point.getY(), paint); } } } } }
private boolean decode( MonochromeBitmapSource source, float rotation, String expectedText, boolean tryHarder) { Result result; String suffix = " (" + (tryHarder ? "try harder, " : "") + "rotation: " + rotation + ')'; try { result = barcodeReader.decode(source, tryHarder ? TRY_HARDER_HINT : null); } catch (ReaderException re) { System.out.println(re + suffix); return false; } if (!expectedFormat.equals(result.getBarcodeFormat())) { System.out.println( "Format mismatch: expected '" + expectedFormat + "' but got '" + result.getBarcodeFormat() + "'" + suffix); return false; } String resultText = result.getText(); if (!expectedText.equals(resultText)) { System.out.println( "Mismatch: expected '" + expectedText + "' but got '" + resultText + "'" + suffix); return false; } return true; }
/** * @param color Color of result points * @return {@link Bitmap} with result points on it, or plain bitmap, if no result points */ public Bitmap getBitmapWithResultPoints(int color) { Bitmap bitmap = getBitmap(); Bitmap barcode = bitmap; ResultPoint[] points = mResult.getResultPoints(); if (points != null && points.length > 0 && bitmap != null) { barcode = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(barcode); canvas.drawBitmap(bitmap, 0, 0, null); Paint paint = new Paint(); paint.setColor(color); if (points.length == 2) { paint.setStrokeWidth(PREVIEW_LINE_WIDTH); drawLine(canvas, paint, points[0], points[1], mScaleFactor); } else if (points.length == 4 && (mResult.getBarcodeFormat() == BarcodeFormat.UPC_A || mResult.getBarcodeFormat() == BarcodeFormat.EAN_13)) { // Hacky special case -- draw two lines, for the barcode and metadata drawLine(canvas, paint, points[0], points[1], mScaleFactor); drawLine(canvas, paint, points[2], points[3], mScaleFactor); } else { paint.setStrokeWidth(PREVIEW_DOT_WIDTH); for (ResultPoint point : points) { if (point != null) { canvas.drawPoint(point.getX() / mScaleFactor, point.getY() / mScaleFactor, paint); } } } } return barcode; }
protected void drawResultPoints(Bitmap barcode, Result rawResult) { ResultPoint[] points = rawResult.getResultPoints(); if (points != null && points.length > 0) { Canvas canvas = new Canvas(barcode); Paint paint = new Paint(); paint.setColor(getResources().getColor(R.color.result_image_border)); paint.setStrokeWidth(3.0f); paint.setStyle(Paint.Style.STROKE); Rect border = new Rect(2, 2, barcode.getWidth() - 2, barcode.getHeight() - 2); canvas.drawRect(border, paint); paint.setColor(getResources().getColor(R.color.result_points)); if (points.length == 2) { paint.setStrokeWidth(4.0f); drawLine(canvas, paint, points[0], points[1]); } else if (points.length == 4 && (rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A || rawResult.getBarcodeFormat() == BarcodeFormat.EAN_13)) { // Hacky special case -- draw two lines, for the barcode and // metadata drawLine(canvas, paint, points[0], points[1]); drawLine(canvas, paint, points[2], points[3]); } else { paint.setStrokeWidth(10.0f); for (ResultPoint point : points) { canvas.drawPoint(point.getX(), point.getY(), paint); } } } }
public void addHistoryItem(Result result, ResultHandler handler) { // Do not save this item to the history if the preference is turned off, or the contents are // considered secure. if (!activity.getIntent().getBooleanExtra(Intents.Scan.SAVE_HISTORY, true) || handler.areContentsSecure() || !enableHistory) { return; } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity); if (!prefs.getBoolean(PreferencesActivity.KEY_REMEMBER_DUPLICATES, false)) { deletePrevious(result.getText()); } ContentValues values = new ContentValues(); values.put(DBHelper.TEXT_COL, result.getText()); values.put(DBHelper.FORMAT_COL, result.getBarcodeFormat().toString()); values.put(DBHelper.DISPLAY_COL, handler.getDisplayContents().toString()); values.put(DBHelper.TIMESTAMP_COL, System.currentTimeMillis()); SQLiteOpenHelper helper = new DBHelper(activity); SQLiteDatabase db = null; try { db = helper.getWritableDatabase(); // Insert the new entry into the DB. db.insert(DBHelper.TABLE_NAME, DBHelper.TIMESTAMP_COL, values); } finally { close(null, db); } }
String fillInCustomSearchURL(String text) { String url = customProductSearch.replace("%s", text); if (rawResult != null) { url = url.replace("%f", rawResult.getBarcodeFormat().toString()); } return url; }
private static void assertCorrectImage2string(String path, String expected) throws IOException, NotFoundException { File file = new File(path); if (!file.exists()) { // Support running from project root too file = new File("core", path); } BufferedImage image = ImageIO.read(file); BinaryBitmap binaryMap = new BinaryBitmap(new GlobalHistogramBinarizer(new BufferedImageLuminanceSource(image))); int rowNumber = binaryMap.getHeight() / 2; BitArray row = binaryMap.getBlackRow(rowNumber, null); Result result; try { RSSExpandedReader rssExpandedReader = new RSSExpandedReader(); result = rssExpandedReader.decodeRow(rowNumber, row, null); } catch (ReaderException re) { fail(re.toString()); return; } assertSame(BarcodeFormat.RSS_EXPANDED, result.getBarcodeFormat()); assertEquals(expected, result.getText()); }
private static Result translateResultPoints(Result result, int xOffset, int yOffset) { ResultPoint[] oldResultPoints = result.getResultPoints(); ResultPoint[] newResultPoints = new ResultPoint[oldResultPoints.length]; for (int i = 0; i < oldResultPoints.length; i++) { ResultPoint oldPoint = oldResultPoints[i]; newResultPoints[i] = new ResultPoint(oldPoint.getX() + xOffset, oldPoint.getY() + yOffset); } return new Result( result.getText(), result.getRawBytes(), newResultPoints, result.getBarcodeFormat()); }
// Briefly show the contents of the barcode, then handle the result outside Barcode Scanner. private void handleDecodeExternally(Result rawResult, Bitmap barcode) { viewfinderView.drawResultBitmap(barcode); // Since this message will only be shown for a second, just tell the user what kind of // barcode was found (e.g. contact info) rather than the full contents, which they won't // have time to read. ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult); statusView.setText(getString(resultHandler.getDisplayTitle())); if (copyToClipboard) { ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); clipboard.setText(resultHandler.getDisplayContents()); } if (source == Source.NATIVE_APP_INTENT) { // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when // the deprecated intent is retired. Intent intent = new Intent(getIntent().getAction()); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.putExtra(Intents.Scan.RESULT, rawResult.toString()); intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString()); // crop barcode bitmap by 5pixels on each side barcode = Bitmap.createBitmap(barcode, 5, 5, barcode.getWidth() - 10, barcode.getHeight() - 10); ByteArrayOutputStream bitmapOutStream = new ByteArrayOutputStream(); barcode.compress(Bitmap.CompressFormat.JPEG, 35, bitmapOutStream); intent.putExtra(Intents.Scan.RESULT_BITMAP_BYTES, bitmapOutStream.toByteArray()); Message message = Message.obtain(handler, R.id.return_scan_result); message.obj = intent; handler.sendMessageDelayed(message, INTENT_RESULT_DURATION); } else if (source == Source.PRODUCT_SEARCH_LINK) { // Reformulate the URL which triggered us into a query, so that the request goes to the same // TLD as the scan URL. Message message = Message.obtain(handler, R.id.launch_product_query); int end = sourceUrl.lastIndexOf("/scan"); message.obj = sourceUrl.substring(0, end) + "?q=" + resultHandler.getDisplayContents().toString() + "&source=zxing"; handler.sendMessageDelayed(message, INTENT_RESULT_DURATION); } else if (source == Source.ZXING_LINK) { // Replace each occurrence of RETURN_CODE_PLACEHOLDER in the returnUrlTemplate // with the scanned code. This allows both queries and REST-style URLs to work. Message message = Message.obtain(handler, R.id.launch_product_query); message.obj = returnUrlTemplate.replace( RETURN_CODE_PLACEHOLDER, resultHandler.getDisplayContents().toString()); handler.sendMessageDelayed(message, INTENT_RESULT_DURATION); } }
// Briefly show the contents of the barcode, then handle the result outside Barcode Scanner. private void handleDecodeExternally( Result rawResult, ResultHandler resultHandler, Bitmap barcode) { viewfinderView.drawResultBitmap(barcode); // Since this message will only be shown for a second, just tell the user what kind of // barcode was found (e.g. contact info) rather than the full contents, which they won't // have time to read. // TODO // TODO statusView.setText(getString(resultHandler.getDisplayTitle())); if (copyToClipboard && !resultHandler.areContentsSecure()) { ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); clipboard.setText(resultHandler.getDisplayContents()); } if (source == Source.NATIVE_APP_INTENT) { // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when // the deprecated intent is retired. Intent intent = new Intent(getIntent().getAction()); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.putExtra(Intents.Scan.RESULT, rawResult.toString()); intent.putExtra("RTN_CONTENT", resultHandler.getDisplayContents()); intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString()); byte[] rawBytes = rawResult.getRawBytes(); if (rawBytes != null && rawBytes.length > 0) { intent.putExtra(Intents.Scan.RESULT_BYTES, rawBytes); } Message message = Message.obtain(handler, R.id.return_scan_result); message.obj = intent; handler.sendMessageDelayed(message, INTENT_RESULT_DURATION); } else if (source == Source.PRODUCT_SEARCH_LINK) { // Reformulate the URL which triggered us into a query, so that the request goes to the same // TLD as the scan URL. Message message = Message.obtain(handler, R.id.launch_product_query); int end = sourceUrl.lastIndexOf("/scan"); message.obj = sourceUrl.substring(0, end) + "?q=" + resultHandler.getDisplayContents().toString() + "&source=zxing"; handler.sendMessageDelayed(message, INTENT_RESULT_DURATION); } else if (source == Source.ZXING_LINK) { // Replace each occurrence of RETURN_CODE_PLACEHOLDER in the returnUrlTemplate // with the scanned code. This allows both queries and REST-style URLs to work. Message message = Message.obtain(handler, R.id.launch_product_query); message.obj = returnUrlTemplate.replace( RETURN_CODE_PLACEHOLDER, resultHandler.getDisplayContents().toString()); handler.sendMessageDelayed(message, INTENT_RESULT_DURATION); } }
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; }
String fillInCustomSearchURL(String text) { if (customProductSearch == null) { return text; // ? } String url = customProductSearch.replace("%s", text); if (rawResult != null) { url = url.replace("%f", rawResult.getBarcodeFormat().toString()); if (url.contains("%t")) { ParsedResult parsedResultAgain = ResultParser.parseResult(rawResult); url = url.replace("%t", parsedResultAgain.getType().toString()); } } return url; }
public void handleDecode(Result result, Bitmap barcode) { inactivityTimer.onActivity(); playBeepSoundAndVibrate(); String resultString = result.getText(); if (resultString.equals("")) { Toast.makeText(CaptureActivity.this, "Scan failed!", Toast.LENGTH_SHORT).show(); } else { Intent resultIntent = new Intent(); Bundle bundle = new Bundle(); bundle.putString(getString(R.string.EXTRA_SCAN_RESULT), resultString); bundle.putInt(getString(R.string.EXTRA_BARCODE_FORMAT), result.getBarcodeFormat().ordinal()); resultIntent.putExtras(bundle); this.setResult(RESULT_OK, resultIntent); } CaptureActivity.this.finish(); }
/** * A valid barcode has been found, so give an indication of success and show the results. * * @param rawResult The contents of the barcode. * @param scaleFactor amount by which thumbnail was scaled * @param barcode A greyscale bitmap of the camera data which was decoded. */ @SuppressWarnings("unchecked") public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) { inactivityTimer.onActivity(); ParsedResult result = ResultParser.parseResult(rawResult); // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when // the deprecated intent is retired. Intent intent = new Intent(getIntent().getAction()); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.putExtra(Intents.Scan.RESULT, result.getDisplayResult()); intent.putExtra(Intents.Scan.RESULT_TYPE, result.getType().ordinal()); intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString()); byte[] rawBytes = bm2bytes(barcode); // byte[] rawBytes = rawResult.getRawBytes(); if (rawBytes != null && rawBytes.length > 0) { intent.putExtra(Intents.Scan.RESULT_BYTES, rawBytes); } Map<ResultMetadataType, ?> metadata = rawResult.getResultMetadata(); if (metadata != null) { if (metadata.containsKey(ResultMetadataType.UPC_EAN_EXTENSION)) { intent.putExtra( Intents.Scan.RESULT_UPC_EAN_EXTENSION, metadata.get(ResultMetadataType.UPC_EAN_EXTENSION).toString()); } Integer orientation = (Integer) metadata.get(ResultMetadataType.ORIENTATION); if (orientation != null) { intent.putExtra(Intents.Scan.RESULT_ORIENTATION, orientation.intValue()); } String ecLevel = (String) metadata.get(ResultMetadataType.ERROR_CORRECTION_LEVEL); if (ecLevel != null) { intent.putExtra(Intents.Scan.RESULT_ERROR_CORRECTION_LEVEL, ecLevel); } Iterable<byte[]> byteSegments = (Iterable<byte[]>) metadata.get(ResultMetadataType.BYTE_SEGMENTS); if (byteSegments != null) { int i = 0; for (byte[] byteSegment : byteSegments) { intent.putExtra(Intents.Scan.RESULT_BYTE_SEGMENTS_PREFIX + i, byteSegment); i++; } } } Message message = Message.obtain(handler, R.id.return_scan_result, intent); handler.sendMessage(message); }
final String fillInCustomSearchURL(String text) { if (customProductSearch == null) { return text; // ? } try { text = URLEncoder.encode(text, "UTF-8"); } catch (UnsupportedEncodingException e) { // can't happen; UTF-8 is always supported. Continue, I guess, without encoding } String url = customProductSearch; if (rawResult != null) { // Replace %f but only if it doesn't seem to be a hex escape sequence. This remains // problematic but avoids the more surprising problem of breaking escapes url = url.replaceFirst("%f(?![0-9a-f])", rawResult.getBarcodeFormat().toString()); if (url.contains("%t")) { ParsedResult parsedResultAgain = ResultParser.parseResult(rawResult); url = url.replace("%t", parsedResultAgain.getType().toString()); } } // Replace %s last as it might contain itself %f or %t return url.replace("%s", text); }
private void operateResult(Result rawResult) { String codeType = rawResult.getBarcodeFormat().toString(); String scanResult = rawResult.getText(); // 二维码 if ("QR_CODE".equals(codeType) || "DATA_MATRIX".equals(codeType)) { boolean isUrl = MyUtil.checkWebSite(scanResult); // 不是标准网址 if (!isUrl) { // 如果是没有添加协议的网址 if (MyUtil.checkWebSitePath(scanResult)) { scanResult = "http://" + scanResult; isUrl = true; } } // 扫描结果为网址 if (isUrl) { try { Intent intent = new Intent("android.intent.action.VIEW"); // intent.addCategory(Intent.CATEGORY_BROWSABLE); Uri uri = Uri.parse(scanResult); intent.setData(uri); myFinish(intent); } catch (Exception e) { LogUtil.e(LOG_TAG, "handleDecode: " + e.toString()); displayResult(scanResult, 0); } } else { displayResult(scanResult, 0); } // 条形码 } else if ("EAN_13".equals(codeType)) { displayResult(scanResult, 1); } else { Snackbar.make(scanContainer, getString(R.string.decode_null), Snackbar.LENGTH_SHORT).show(); } }
// Briefly show the contents of the barcode, then handle the result outside Barcode Scanner. private void handleDecodeExternally( Result rawResult, ResultHandler resultHandler, Bitmap barcode) { if (barcode != null) { viewfinderView.drawResultBitmap(barcode); } long resultDurationMS; if (getIntent() == null) { resultDurationMS = DEFAULT_INTENT_RESULT_DURATION_MS; } else { resultDurationMS = getIntent() .getLongExtra( Intents.Scan.RESULT_DISPLAY_DURATION_MS, DEFAULT_INTENT_RESULT_DURATION_MS); } if (resultDurationMS > 0) { String rawResultString = String.valueOf(rawResult); if (rawResultString.length() > 32) { rawResultString = rawResultString.substring(0, 32) + " ..."; } statusView.setText(getString(resultHandler.getDisplayTitle()) + " : " + rawResultString); } if (copyToClipboard && !resultHandler.areContentsSecure()) { CharSequence text = resultHandler.getDisplayContents(); ClipboardInterface.setText(text, this); } if (source == IntentSource.NATIVE_APP_INTENT) { // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when // the deprecated intent is retired. Intent intent = new Intent(getIntent().getAction()); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.putExtra(Intents.Scan.RESULT, rawResult.toString()); intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString()); byte[] rawBytes = rawResult.getRawBytes(); if (rawBytes != null && rawBytes.length > 0) { intent.putExtra(Intents.Scan.RESULT_BYTES, rawBytes); } Map<ResultMetadataType, ?> metadata = rawResult.getResultMetadata(); if (metadata != null) { if (metadata.containsKey(ResultMetadataType.UPC_EAN_EXTENSION)) { intent.putExtra( Intents.Scan.RESULT_UPC_EAN_EXTENSION, metadata.get(ResultMetadataType.UPC_EAN_EXTENSION).toString()); } Number orientation = (Number) metadata.get(ResultMetadataType.ORIENTATION); if (orientation != null) { intent.putExtra(Intents.Scan.RESULT_ORIENTATION, orientation.intValue()); } String ecLevel = (String) metadata.get(ResultMetadataType.ERROR_CORRECTION_LEVEL); if (ecLevel != null) { intent.putExtra(Intents.Scan.RESULT_ERROR_CORRECTION_LEVEL, ecLevel); } @SuppressWarnings("unchecked") Iterable<byte[]> byteSegments = (Iterable<byte[]>) metadata.get(ResultMetadataType.BYTE_SEGMENTS); if (byteSegments != null) { int i = 0; for (byte[] byteSegment : byteSegments) { intent.putExtra(Intents.Scan.RESULT_BYTE_SEGMENTS_PREFIX + i, byteSegment); i++; } } } sendReplyMessage(R.id.return_scan_result, intent, resultDurationMS); } else if (source == IntentSource.PRODUCT_SEARCH_LINK) { // Reformulate the URL which triggered us into a query, so that the request goes to the same // TLD as the scan URL. int end = sourceUrl.lastIndexOf("/scan"); String replyURL = sourceUrl.substring(0, end) + "?q=" + resultHandler.getDisplayContents() + "&source=zxing"; sendReplyMessage(R.id.launch_product_query, replyURL, resultDurationMS); } else if (source == IntentSource.ZXING_LINK) { if (scanFromWebPageManager != null && scanFromWebPageManager.isScanFromWebPage()) { String replyURL = scanFromWebPageManager.buildReplyURL(rawResult, resultHandler); sendReplyMessage(R.id.launch_product_query, replyURL, resultDurationMS); } } }
// Put up our own UI for how to handle the decoded contents. private void handleDecodeInternally( Result rawResult, ResultHandler resultHandler, Bitmap barcode) { statusView.setVisibility(View.GONE); viewfinderView.setVisibility(View.GONE); resultView.setVisibility(View.VISIBLE); ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view); if (barcode == null) { barcodeImageView.setImageBitmap( BitmapFactory.decodeResource(getResources(), R.drawable.launcher_icon)); } else { barcodeImageView.setImageBitmap(barcode); } TextView formatTextView = (TextView) findViewById(R.id.format_text_view); formatTextView.setText(rawResult.getBarcodeFormat().toString()); TextView typeTextView = (TextView) findViewById(R.id.type_text_view); typeTextView.setText(resultHandler.getType().toString()); DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); TextView timeTextView = (TextView) findViewById(R.id.time_text_view); timeTextView.setText(formatter.format(new Date(rawResult.getTimestamp()))); TextView metaTextView = (TextView) findViewById(R.id.meta_text_view); View metaTextViewLabel = findViewById(R.id.meta_text_view_label); metaTextView.setVisibility(View.GONE); metaTextViewLabel.setVisibility(View.GONE); Map<ResultMetadataType, Object> metadata = rawResult.getResultMetadata(); if (metadata != null) { StringBuilder metadataText = new StringBuilder(20); for (Map.Entry<ResultMetadataType, Object> entry : metadata.entrySet()) { if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) { metadataText.append(entry.getValue()).append('\n'); } } if (metadataText.length() > 0) { metadataText.setLength(metadataText.length() - 1); metaTextView.setText(metadataText); metaTextView.setVisibility(View.VISIBLE); metaTextViewLabel.setVisibility(View.VISIBLE); } } TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view); CharSequence displayContents = resultHandler.getDisplayContents(); final String sptm = displayContents.toString().trim(); // 2013-12-09,cj,显示药品详情 SpkfkService spService = new SpkfkService(CaptureActivity.this); final AdvSpkfk sp = spService.getByBarcode(displayContents.toString()); if (sp != null) { displayContents = displayContents + "\n" + spService.toString(sp); } else { displayContents = displayContents + "\n未找到相关商品"; } contentsTextView.setText(displayContents); // Crudely scale betweeen 22 and 32 -- bigger font for shorter text int scaledSize = Math.max(22, 32 - displayContents.length() / 4); contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize); /*2013-12-10,cj,简化,此处查询尝试去亚马逊查询商品信息 TextView supplementTextView = (TextView) findViewById(R.id.contents_supplement_text_view); supplementTextView.setText(""); supplementTextView.setOnClickListener(null); if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean( PreferencesActivity.KEY_SUPPLEMENTAL, true)) { SupplementalInfoRetriever.maybeInvokeRetrieval(supplementTextView, resultHandler.getResult(), historyManager, this); } */ // 2013-12-09,cj,添加,设置回退按钮,功能同按返回键 ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view); buttonView.requestFocus(); for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) { TextView button = (TextView) buttonView.getChildAt(x); if (x == 0) { button.setVisibility(View.VISIBLE); button.setText("继续扫码"); button.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { restartPreviewAfterDelay(BULK_MODE_SCAN_DELAY_MS); } }); } else if (x == 1) { String btnText = ""; if (sp == null) { btnText = "寻找商品"; } else { btnText = "商品资料"; } button.setVisibility(View.VISIBLE); button.setText(btnText); button.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { if (sp == null) { Intent intent = new Intent(CaptureActivity.this, SpkfkSelectActivity.class); intent.setFlags(SpkfkSelectActivity.FLAG_FIND_SP); intent.putExtra(EXTRA_NAME_SPTM, sptm); startActivity(intent); } else { // TODO Toast.makeText(CaptureActivity.this, "暂未实现功能", Toast.LENGTH_LONG).show(); // 启动商品详情activity Intent intent = new Intent(CaptureActivity.this, SpkfkDetailActivity.class); intent.putExtra(SpkfkDetailActivity.EXTRA_NAME_SPKFK, sp); startActivity(intent); } // restartPreviewAfterDelay(BULK_MODE_SCAN_DELAY_MS); } }); } else { button.setVisibility(View.GONE); } } /*2013-12-10,cj,简化,此处根据条码类型来显示不同的按钮 int buttonCount = resultHandler.getButtonCount(); ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view); buttonView.requestFocus(); for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) { TextView button = (TextView) buttonView.getChildAt(x); if (x < buttonCount) { button.setVisibility(View.VISIBLE); button.setText(resultHandler.getButtonText(x)); button.setOnClickListener(new ResultButtonListener(resultHandler, x)); } else { button.setVisibility(View.GONE); } } */ if (copyToClipboard && !resultHandler.areContentsSecure()) { ClipboardInterface.setText(displayContents, this); } }
/** * @return {@link BarcodeFormat} representing the format of the barcode that was decoded * @see Result#getBarcodeFormat() */ public BarcodeFormat getBarcodeFormat() { return mResult.getBarcodeFormat(); }
public void handleDecode(Result paramResult, Bitmap paramBitmap) { this.inactivityTimer.onActivity(); this.viewfinderView.drawResultBitmap(paramBitmap); playBeepSoundAndVibrate(); this.txtResult.setText(paramResult.getBarcodeFormat().toString() + ":" + paramResult.getText()); }
// Put up our own UI for how to handle the decoded contents. private void handleDecodeInternally(Result rawResult, Bitmap barcode) { statusView.setVisibility(View.GONE); viewfinderView.setVisibility(View.GONE); resultView.setVisibility(View.VISIBLE); ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view); if (barcode == null) { // barcodeImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), // R.drawable.launcher_icon)); } else { barcodeImageView.setImageBitmap(barcode); } TextView formatTextView = (TextView) findViewById(R.id.format_text_view); formatTextView.setText(rawResult.getBarcodeFormat().toString()); ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult); TextView typeTextView = (TextView) findViewById(R.id.type_text_view); typeTextView.setText(resultHandler.getType().toString()); DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); String formattedTime = formatter.format(new Date(rawResult.getTimestamp())); TextView timeTextView = (TextView) findViewById(R.id.time_text_view); timeTextView.setText(formattedTime); TextView metaTextView = (TextView) findViewById(R.id.meta_text_view); View metaTextViewLabel = findViewById(R.id.meta_text_view_label); metaTextView.setVisibility(View.GONE); metaTextViewLabel.setVisibility(View.GONE); Map<ResultMetadataType, Object> metadata = (Map<ResultMetadataType, Object>) rawResult.getResultMetadata(); if (metadata != null) { StringBuilder metadataText = new StringBuilder(20); for (Map.Entry<ResultMetadataType, Object> entry : metadata.entrySet()) { if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) { metadataText.append(entry.getValue()).append('\n'); } } if (metadataText.length() > 0) { metadataText.setLength(metadataText.length() - 1); metaTextView.setText(metadataText); metaTextView.setVisibility(View.VISIBLE); metaTextViewLabel.setVisibility(View.VISIBLE); } } TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view); CharSequence displayContents = resultHandler.getDisplayContents(); contentsTextView.setText(displayContents); // Crudely scale betweeen 22 and 32 -- bigger font for shorter text int scaledSize = Math.max(22, 32 - displayContents.length() / 4); contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize); /* int buttonCount = resultHandler.getButtonCount(); ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view); buttonView.requestFocus(); for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) { TextView button = (TextView) buttonView.getChildAt(x); if (x < buttonCount) { button.setVisibility(View.VISIBLE); button.setText(resultHandler.getButtonText(x)); button.setOnClickListener(new ResultButtonListener(resultHandler, x)); } else { button.setVisibility(View.GONE); } } */ if (copyToClipboard) { ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); clipboard.setText(displayContents); } }
// Briefly show the contents of the barcode, then handle the result outside Barcode Scanner. private void handleDecodeExternally( Result rawResult, ResultHandler resultHandler, Bitmap barcode) { if (barcode != null) { viewfinderView.drawResultBitmap(barcode); } long resultDurationMS; if (getIntent() == null) { resultDurationMS = DEFAULT_INTENT_RESULT_DURATION_MS; } else { resultDurationMS = getIntent() .getLongExtra( Intents.Scan.RESULT_DISPLAY_DURATION_MS, DEFAULT_INTENT_RESULT_DURATION_MS); } // Since this message will only be shown for a second, just tell the user what kind of // barcode was found (e.g. contact info) rather than the full contents, which they won't // have time to read. if (resultDurationMS > 0) { statusView.setText(getString(resultHandler.getDisplayTitle())); } if (copyToClipboard && !resultHandler.areContentsSecure()) { ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); CharSequence text = resultHandler.getDisplayContents(); if (text != null) { clipboard.setText(text); } } if (source == IntentSource.NATIVE_APP_INTENT) { // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when // the deprecated intent is retired. Intent intent = new Intent(getIntent().getAction()); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.putExtra(Intents.Scan.RESULT, rawResult.toString()); intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString()); byte[] rawBytes = rawResult.getRawBytes(); if (rawBytes != null && rawBytes.length > 0) { intent.putExtra(Intents.Scan.RESULT_BYTES, rawBytes); } Map<ResultMetadataType, ?> metadata = rawResult.getResultMetadata(); if (metadata != null) { if (metadata.containsKey(ResultMetadataType.UPC_EAN_EXTENSION)) { intent.putExtra( Intents.Scan.RESULT_UPC_EAN_EXTENSION, metadata.get(ResultMetadataType.UPC_EAN_EXTENSION).toString()); } Integer orientation = (Integer) metadata.get(ResultMetadataType.ORIENTATION); if (orientation != null) { intent.putExtra(Intents.Scan.RESULT_ORIENTATION, orientation.intValue()); } String ecLevel = (String) metadata.get(ResultMetadataType.ERROR_CORRECTION_LEVEL); if (ecLevel != null) { intent.putExtra(Intents.Scan.RESULT_ERROR_CORRECTION_LEVEL, ecLevel); } Iterable<byte[]> byteSegments = (Iterable<byte[]>) metadata.get(ResultMetadataType.BYTE_SEGMENTS); if (byteSegments != null) { int i = 0; for (byte[] byteSegment : byteSegments) { intent.putExtra(Intents.Scan.RESULT_BYTE_SEGMENTS_PREFIX + i, byteSegment); i++; } } } sendReplyMessage(fakeR.getId("id", "return_scan_result"), intent, resultDurationMS); } else if (source == IntentSource.PRODUCT_SEARCH_LINK) { // Reformulate the URL which triggered us into a query, so that the request goes to the same // TLD as the scan URL. int end = sourceUrl.lastIndexOf("/scan"); String replyURL = sourceUrl.substring(0, end) + "?q=" + resultHandler.getDisplayContents() + "&source=zxing"; sendReplyMessage(fakeR.getId("id", "launch_product_query"), replyURL, resultDurationMS); } else if (source == IntentSource.ZXING_LINK) { // Replace each occurrence of RETURN_CODE_PLACEHOLDER in the returnUrlTemplate // with the scanned code. This allows both queries and REST-style URLs to work. if (returnUrlTemplate != null) { CharSequence codeReplacement = returnRaw ? rawResult.getText() : resultHandler.getDisplayContents(); try { codeReplacement = URLEncoder.encode(codeReplacement.toString(), "UTF-8"); } catch (UnsupportedEncodingException e) { // can't happen; UTF-8 is always supported. Continue, I guess, without encoding } String replyURL = returnUrlTemplate.replace(RETURN_CODE_PLACEHOLDER, codeReplacement); sendReplyMessage(fakeR.getId("id", "launch_product_query"), replyURL, resultDurationMS); } } }
// Put up our own UI for how to handle the decoded contents. private void handleDecodeInternally( Result rawResult, ResultHandler resultHandler, Bitmap barcode) { statusView.setVisibility(View.GONE); viewfinderView.setVisibility(View.GONE); resultView.setVisibility(View.VISIBLE); ImageView barcodeImageView = (ImageView) findViewById(fakeR.getId("id", "barcode_image_view")); if (barcode == null) { barcodeImageView.setImageBitmap( BitmapFactory.decodeResource(getResources(), fakeR.getId("drawable", "launcher_icon"))); } else { barcodeImageView.setImageBitmap(barcode); } TextView formatTextView = (TextView) findViewById(fakeR.getId("id", "format_text_view")); formatTextView.setText(rawResult.getBarcodeFormat().toString()); TextView typeTextView = (TextView) findViewById(fakeR.getId("id", "type_text_view")); typeTextView.setText(resultHandler.getType().toString()); DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); String formattedTime = formatter.format(new Date(rawResult.getTimestamp())); TextView timeTextView = (TextView) findViewById(fakeR.getId("id", "time_text_view")); timeTextView.setText(formattedTime); TextView metaTextView = (TextView) findViewById(fakeR.getId("id", "meta_text_view")); View metaTextViewLabel = findViewById(fakeR.getId("id", "meta_text_view_label")); metaTextView.setVisibility(View.GONE); metaTextViewLabel.setVisibility(View.GONE); Map<ResultMetadataType, Object> metadata = rawResult.getResultMetadata(); if (metadata != null) { StringBuilder metadataText = new StringBuilder(20); for (Map.Entry<ResultMetadataType, Object> entry : metadata.entrySet()) { if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) { metadataText.append(entry.getValue()).append('\n'); } } if (metadataText.length() > 0) { metadataText.setLength(metadataText.length() - 1); metaTextView.setText(metadataText); metaTextView.setVisibility(View.VISIBLE); metaTextViewLabel.setVisibility(View.VISIBLE); } } TextView contentsTextView = (TextView) findViewById(fakeR.getId("id", "contents_text_view")); CharSequence displayContents = resultHandler.getDisplayContents(); contentsTextView.setText(displayContents); // Crudely scale betweeen 22 and 32 -- bigger font for shorter text int scaledSize = Math.max(22, 32 - displayContents.length() / 4); contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize); TextView supplementTextView = (TextView) findViewById(fakeR.getId("id", "contents_supplement_text_view")); supplementTextView.setText(""); supplementTextView.setOnClickListener(null); if (PreferenceManager.getDefaultSharedPreferences(this) .getBoolean(PreferencesActivity.KEY_SUPPLEMENTAL, true)) { SupplementalInfoRetriever.maybeInvokeRetrieval( supplementTextView, resultHandler.getResult(), historyManager, this); } int buttonCount = resultHandler.getButtonCount(); ViewGroup buttonView = (ViewGroup) findViewById(fakeR.getId("id", "result_button_view")); buttonView.requestFocus(); for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) { TextView button = (TextView) buttonView.getChildAt(x); if (x < buttonCount) { button.setVisibility(View.VISIBLE); button.setText(resultHandler.getButtonText(x)); button.setOnClickListener(new ResultButtonListener(resultHandler, x)); } else { button.setVisibility(View.GONE); } } if (copyToClipboard && !resultHandler.areContentsSecure()) { ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); if (displayContents != null) { clipboard.setText(displayContents); } } }
// Put up our own UI for how to handle the decoded contents. private void handleDecodeInternally( Result rawResult, ResultHandler resultHandler, Bitmap barcode) { CharSequence displayContents = resultHandler.getDisplayContents(); if (copyToClipboard && !resultHandler.areContentsSecure()) { ClipboardInterface.setText(displayContents, this); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (resultHandler.getDefaultButtonID() != null && prefs.getBoolean(PreferencesActivity.KEY_AUTO_OPEN_WEB, false)) { resultHandler.handleButtonPress(resultHandler.getDefaultButtonID()); return; } statusView.setVisibility(View.GONE); viewfinderView.setVisibility(View.GONE); resultView.setVisibility(View.VISIBLE); ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view); if (barcode == null) { barcodeImageView.setImageBitmap( BitmapFactory.decodeResource(getResources(), R.drawable.launcher_icon)); } else { barcodeImageView.setImageBitmap(barcode); } TextView formatTextView = (TextView) findViewById(R.id.format_text_view); formatTextView.setText(rawResult.getBarcodeFormat().toString()); TextView typeTextView = (TextView) findViewById(R.id.type_text_view); typeTextView.setText(resultHandler.getType().toString()); DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); TextView timeTextView = (TextView) findViewById(R.id.time_text_view); timeTextView.setText(formatter.format(new Date(rawResult.getTimestamp()))); TextView metaTextView = (TextView) findViewById(R.id.meta_text_view); View metaTextViewLabel = findViewById(R.id.meta_text_view_label); metaTextView.setVisibility(View.GONE); metaTextViewLabel.setVisibility(View.GONE); Map<ResultMetadataType, Object> metadata = rawResult.getResultMetadata(); if (metadata != null) { StringBuilder metadataText = new StringBuilder(20); for (Map.Entry<ResultMetadataType, Object> entry : metadata.entrySet()) { if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) { metadataText.append(entry.getValue()).append('\n'); } } if (metadataText.length() > 0) { metadataText.setLength(metadataText.length() - 1); metaTextView.setText(metadataText); metaTextView.setVisibility(View.VISIBLE); metaTextViewLabel.setVisibility(View.VISIBLE); } } TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view); contentsTextView.setText(displayContents); int scaledSize = Math.max(22, 32 - displayContents.length() / 4); contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize); TextView supplementTextView = (TextView) findViewById(R.id.contents_supplement_text_view); supplementTextView.setText(""); supplementTextView.setOnClickListener(null); // if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean( // PreferencesActivity.KEY_SUPPLEMENTAL, true)) { // SupplementalInfoRetriever.maybeInvokeRetrieval(supplementTextView, // resultHandler.getResult(), // historyManager, // this); // } int buttonCount = resultHandler.getButtonCount(); ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view); buttonView.requestFocus(); for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) { TextView button = (TextView) buttonView.getChildAt(x); if (x < buttonCount) { button.setVisibility(View.VISIBLE); button.setText(resultHandler.getButtonText(x)); button.setOnClickListener(new ResultButtonListener(resultHandler, x)); } else { button.setVisibility(View.GONE); } } }