CaptureActivity.java 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  1. /*
  2. * Copyright (C) 2008 ZXing authors
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.usai.redant.photo;
  17. import com.google.zxing.BarcodeFormat;
  18. import com.google.zxing.DecodeHintType;
  19. import com.google.zxing.Result;
  20. import com.google.zxing.ResultPoint;
  21. import com.google.zxing.client.result.ResultParser;
  22. import com.usai.redant.camera.CameraManager;
  23. import com.usai.util.dbgUtil;
  24. import android.app.Activity;
  25. import android.app.AlertDialog;
  26. import android.content.Intent;
  27. import android.content.pm.ActivityInfo;
  28. //import android.content.SharedPreferences;
  29. import android.graphics.Bitmap;
  30. import android.graphics.Canvas;
  31. import android.graphics.Color;
  32. import android.graphics.Paint;
  33. import android.os.Bundle;
  34. import android.os.Handler;
  35. import android.os.Message;
  36. import android.preference.PreferenceManager;
  37. import android.util.Log;
  38. import android.view.KeyEvent;
  39. import android.view.Menu;
  40. import android.view.MenuInflater;
  41. import android.view.MenuItem;
  42. import android.view.SurfaceHolder;
  43. import android.view.SurfaceView;
  44. import android.view.View;
  45. import android.view.View.OnClickListener;
  46. import android.view.Window;
  47. import android.view.WindowManager;
  48. import android.widget.Button;
  49. import android.widget.TextView;
  50. import java.io.IOException;
  51. import java.util.Collection;
  52. import java.util.Map;
  53. import java.util.Timer;
  54. import java.util.TimerTask;
  55. /**
  56. * This activity opens the camera and does the actual scanning on a background
  57. * thread. It draws a viewfinder to help the user place the barcode correctly,
  58. * shows feedback as the image processing is happening, and then overlays the
  59. * results when a scan is successful.
  60. *
  61. * @author dswitkin@google.com (Daniel Switkin)
  62. * @author Sean Owen
  63. */
  64. public final class CaptureActivity extends Activity implements
  65. SurfaceHolder.Callback
  66. {
  67. private static final String TAG = CaptureActivity.class
  68. .getSimpleName();
  69. // private static final long DEFAULT_INTENT_RESULT_DURATION_MS = 1500L;
  70. // private static final long BULK_MODE_SCAN_DELAY_MS = 1000L;
  71. // private static final String[] ZXING_URLS = {
  72. // "http://zxing.appspot.com/scan", "zxing://scan/" };
  73. // public static final int HISTORY_REQUEST_CODE = 0x0000bacc;
  74. // private static final Collection<ResultMetadataType>
  75. // DISPLAYABLE_METADATA_TYPES =
  76. // EnumSet.of(ResultMetadataType.ISSUE_NUMBER,
  77. // ResultMetadataType.SUGGESTED_PRICE,
  78. // ResultMetadataType.ERROR_CORRECTION_LEVEL,
  79. // ResultMetadataType.POSSIBLE_COUNTRY);
  80. private CameraManager cameraManager;
  81. private CaptureActivityHandler handler;
  82. private Result savedResultToShow;
  83. private ViewfinderView viewfinderView;
  84. private TextView statusView;
  85. // private View resultView;
  86. private Result lastResult;
  87. private boolean hasSurface;
  88. // private boolean copyToClipboard;
  89. // private IntentSource source;
  90. // private String sourceUrl;
  91. // private ScanFromWebPageManager scanFromWebPageManager;
  92. private Collection<BarcodeFormat> decodeFormats;
  93. private Map<DecodeHintType, ?> decodeHints;
  94. private String characterSet;
  95. // private HistoryManager historyManager;
  96. private InactivityTimer inactivityTimer;
  97. private BeepManager beepManager;
  98. private AmbientLightManager ambientLightManager;
  99. ViewfinderView getViewfinderView()
  100. {
  101. return viewfinderView;
  102. }
  103. public Handler getHandler()
  104. {
  105. return handler;
  106. }
  107. CameraManager getCameraManager()
  108. {
  109. return cameraManager;
  110. }
  111. Button swith_button;
  112. @Override
  113. public void onCreate(Bundle icicle)
  114. {
  115. dbgUtil.Logd(TAG, "==============>CaptureActivity created!");
  116. super.onCreate(icicle);
  117. Window window = getWindow();
  118. window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  119. setContentView(R.layout.capture);
  120. swith_button = (Button) findViewById(R.id.btn_switch);
  121. swith_button.setTag("false");
  122. swith_button.setBackgroundColor(getResources().getColor(
  123. R.color.message_fail));
  124. swith_button.setOnClickListener(new OnClickListener()
  125. {
  126. @Override
  127. public void onClick(View v)
  128. {
  129. // inactivityTimer.onPause();
  130. if (Boolean.parseBoolean(v.getTag().toString()) == false)
  131. {
  132. // inactivityTimer.onResume();
  133. v.setTag("true");
  134. v.setBackgroundColor(getResources().getColor(
  135. R.color.message_success));
  136. }
  137. else
  138. {
  139. // inactivityTimer.onPause();
  140. v.setTag("false");
  141. v.setBackgroundColor(getResources().getColor(
  142. R.color.message_fail));
  143. }
  144. }
  145. });
  146. // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
  147. hasSurface = false;
  148. // historyManager = new HistoryManager(this);
  149. // historyManager.trimHistory();
  150. inactivityTimer = new InactivityTimer(this);
  151. beepManager = new BeepManager(this);
  152. ambientLightManager = new AmbientLightManager(this);
  153. // PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
  154. Log.d(TAG, "finish oncreate");
  155. }
  156. @Override
  157. protected void onResume()
  158. {
  159. super.onResume();
  160. // CameraManager must be initialized here, not in onCreate(). This is
  161. // necessary because we don't
  162. // want to open the camera driver and measure the screen size if we're
  163. // going to show the help on
  164. // first launch. That led to bugs where the scanning rectangle was the
  165. // wrong size and partially
  166. // off screen.
  167. cameraManager = new CameraManager(getApplication());
  168. viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
  169. viewfinderView.setCameraManager(cameraManager);
  170. // resultView = findViewById(R.id.result_view);
  171. statusView = (TextView) findViewById(R.id.status_view);
  172. handler = null;
  173. lastResult = null;
  174. resetStatusView();
  175. SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
  176. SurfaceHolder surfaceHolder = surfaceView.getHolder();
  177. if (hasSurface)
  178. {
  179. // The activity was paused but not stopped, so the surface still
  180. // exists. Therefore
  181. // surfaceCreated() won't be called, so init the camera here.
  182. initCamera(surfaceHolder);
  183. }
  184. else
  185. {
  186. // Install the callback and wait for surfaceCreated() to init the
  187. // camera.
  188. surfaceHolder.addCallback(this);
  189. }
  190. beepManager.updatePrefs();
  191. ambientLightManager.start(cameraManager);
  192. inactivityTimer.onResume();
  193. Intent intent = getIntent();
  194. // SharedPreferences prefs =
  195. // PreferenceManager.getDefaultSharedPreferences(this);
  196. // copyToClipboard =
  197. // prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true)
  198. // && (intent == null ||
  199. // intent.getBooleanExtra(Intents.Scan.SAVE_HISTORY, true));
  200. // source = IntentSource.NONE;
  201. decodeFormats = null;
  202. characterSet = null;
  203. if (intent != null)
  204. {
  205. String action = intent.getAction();
  206. // String dataString = intent.getDataString();
  207. if (Intents.Scan.ACTION.equals(action))
  208. {
  209. // Scan the formats the intent requested, and return the result
  210. // to the calling activity.
  211. // source = IntentSource.NATIVE_APP_INTENT;
  212. decodeFormats = DecodeFormatManager.parseDecodeFormats(intent);
  213. decodeHints = DecodeHintManager.parseDecodeHints(intent);
  214. if (intent.hasExtra(Intents.Scan.WIDTH)
  215. && intent.hasExtra(Intents.Scan.HEIGHT))
  216. {
  217. int width = intent.getIntExtra(Intents.Scan.WIDTH, 0);
  218. int height = intent.getIntExtra(Intents.Scan.HEIGHT, 0);
  219. if (width > 0 && height > 0)
  220. {
  221. cameraManager.setManualFramingRect(width, height);
  222. }
  223. }
  224. String customPromptMessage = intent
  225. .getStringExtra(Intents.Scan.PROMPT_MESSAGE);
  226. if (customPromptMessage != null)
  227. {
  228. statusView.setText(customPromptMessage);
  229. }
  230. }
  231. // else if (dataString != null &&
  232. // dataString.contains("http://www.google") &&
  233. // dataString.contains("/m/products/scan")) {
  234. //
  235. // // Scan only products and send the result to mobile Product
  236. // Search.
  237. // // source = IntentSource.PRODUCT_SEARCH_LINK;
  238. // sourceUrl = dataString;
  239. // decodeFormats = DecodeFormatManager.PRODUCT_FORMATS;
  240. //
  241. // }
  242. // else if (isZXingURL(dataString)) {
  243. //
  244. // // Scan formats requested in query string (all formats if none
  245. // specified).
  246. // // If a return URL is specified, send the results there.
  247. // Otherwise, handle it ourselves.
  248. // source = IntentSource.ZXING_LINK;
  249. // sourceUrl = dataString;
  250. // Uri inputUri = Uri.parse(dataString);
  251. // scanFromWebPageManager = new ScanFromWebPageManager(inputUri);
  252. // decodeFormats = DecodeFormatManager.parseDecodeFormats(inputUri);
  253. // // Allow a sub-set of the hints to be specified by the caller.
  254. // decodeHints = DecodeHintManager.parseDecodeHints(inputUri);
  255. //
  256. // }
  257. characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);
  258. }
  259. }
  260. // private static boolean isZXingURL(String dataString) {
  261. // if (dataString == null) {
  262. // return false;
  263. // }
  264. // for (String url : ZXING_URLS) {
  265. // if (dataString.startsWith(url)) {
  266. // return true;
  267. // }
  268. // }
  269. // return false;
  270. // }
  271. @Override
  272. protected void onPause()
  273. {
  274. if (handler != null)
  275. {
  276. handler.quitSynchronously();
  277. handler = null;
  278. }
  279. inactivityTimer.onPause();
  280. ambientLightManager.stop();
  281. cameraManager.closeDriver();
  282. if (!hasSurface)
  283. {
  284. SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
  285. SurfaceHolder surfaceHolder = surfaceView.getHolder();
  286. surfaceHolder.removeCallback(this);
  287. }
  288. super.onPause();
  289. }
  290. @Override
  291. protected void onDestroy()
  292. {
  293. inactivityTimer.shutdown();
  294. super.onDestroy();
  295. }
  296. @Override
  297. public boolean onKeyDown(int keyCode, KeyEvent event)
  298. {
  299. switch (keyCode)
  300. {
  301. // case KeyEvent.KEYCODE_BACK:
  302. // if (source == IntentSource.NATIVE_APP_INTENT) {
  303. // setResult(RESULT_CANCELED);
  304. // finish();
  305. // return true;
  306. // }
  307. // if ((source == IntentSource.NONE || source ==
  308. // IntentSource.ZXING_LINK) && lastResult != null) {
  309. // restartPreviewAfterDelay(0L);
  310. // return true;
  311. // }
  312. // break;
  313. case KeyEvent.KEYCODE_FOCUS:
  314. case KeyEvent.KEYCODE_CAMERA:
  315. // Handle these events so they don't launch the Camera app
  316. return true;
  317. // Use volume up/down to turn on light
  318. case KeyEvent.KEYCODE_VOLUME_DOWN:
  319. cameraManager.setTorch(false);
  320. return true;
  321. case KeyEvent.KEYCODE_VOLUME_UP:
  322. cameraManager.setTorch(true);
  323. return true;
  324. }
  325. return super.onKeyDown(keyCode, event);
  326. }
  327. // @Override
  328. // public boolean onCreateOptionsMenu(Menu menu)
  329. // {
  330. // MenuInflater menuInflater = getMenuInflater();
  331. // menuInflater.inflate(R.menu.capture, menu);
  332. // return super.onCreateOptionsMenu(menu);
  333. // }
  334. //
  335. // @Override
  336. // public boolean onOptionsItemSelected(MenuItem item)
  337. // {
  338. // Intent intent = new Intent(Intent.ACTION_VIEW);
  339. // intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
  340. // switch (item.getItemId())
  341. // {
  342. // // case R.id.menu_share:
  343. // // intent.setClassName(this, ShareActivity.class.getName());
  344. // // startActivity(intent);
  345. // // break;
  346. // // case R.id.menu_history:
  347. // // intent.setClassName(this, HistoryActivity.class.getName());
  348. // // startActivityForResult(intent, HISTORY_REQUEST_CODE);
  349. // // break;
  350. // case R.id.menu_settings:
  351. // intent.setClassName(this, PreferencesActivity.class.getName());
  352. // startActivity(intent);
  353. // break;
  354. // // case R.id.menu_help:
  355. // // intent.setClassName(this, HelpActivity.class.getName());
  356. // // startActivity(intent);
  357. // // break;
  358. // default:
  359. // return super.onOptionsItemSelected(item);
  360. // }
  361. // return true;
  362. // }
  363. // @Override
  364. // public void onActivityResult(int requestCode, int resultCode, Intent
  365. // intent) {
  366. // if (resultCode == RESULT_OK) {
  367. // // if (requestCode == HISTORY_REQUEST_CODE)
  368. // // {
  369. // // int itemNumber = intent.getIntExtra(Intents.History.ITEM_NUMBER, -1);
  370. // // if (itemNumber >= 0) {
  371. // // HistoryItem historyItem = historyManager.buildHistoryItem(itemNumber);
  372. // // decodeOrStoreSavedBitmap(null, historyItem.getResult());
  373. // // }
  374. // // }
  375. // }
  376. // }
  377. private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result)
  378. {
  379. // Bitmap isn't used yet -- will be used soon
  380. if (handler == null)
  381. {
  382. savedResultToShow = result;
  383. }
  384. else
  385. {
  386. if (result != null)
  387. {
  388. savedResultToShow = result;
  389. }
  390. if (savedResultToShow != null)
  391. {
  392. Message message = Message.obtain(handler,
  393. R.id.decode_succeeded, savedResultToShow);
  394. handler.sendMessage(message);
  395. }
  396. savedResultToShow = null;
  397. }
  398. }
  399. @Override
  400. public void surfaceCreated(SurfaceHolder holder)
  401. {
  402. if (holder == null)
  403. {
  404. Log.d(TAG,
  405. "*** WARNING *** surfaceCreated() gave us a null surface!");
  406. }
  407. if (!hasSurface)
  408. {
  409. hasSurface = true;
  410. initCamera(holder);
  411. }
  412. }
  413. @Override
  414. public void surfaceDestroyed(SurfaceHolder holder)
  415. {
  416. hasSurface = false;
  417. }
  418. @Override
  419. public void surfaceChanged(SurfaceHolder holder, int format, int width,
  420. int height)
  421. {
  422. }
  423. /**
  424. * A valid barcode has been found, so give an indication of success and show
  425. * the results.
  426. *
  427. * @param rawResult
  428. * The contents of the barcode.
  429. * @param scaleFactor
  430. * amount by which thumbnail was scaled
  431. * @param barcode
  432. * A greyscale bitmap of the camera data which was decoded.
  433. */
  434. public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor)
  435. {
  436. String tag = swith_button.getTag().toString();
  437. if (Boolean.parseBoolean(tag) == false)
  438. {
  439. restartPreviewAfterDelay(0L);
  440. return;
  441. }
  442. inactivityTimer.onActivity();
  443. lastResult = rawResult;
  444. TextView debugTextView = (TextView) findViewById(R.id.textView1);
  445. debugTextView.setText(rawResult.getText());
  446. // ResultHandler resultHandler =
  447. // ResultHandlerFactory.makeResultHandler(this, rawResult);
  448. Log.i(TAG, "RESULT=========>" + rawResult.getText().toString());
  449. // ParsedResult result = parseResult(rawResult);
  450. Log.i(TAG, "HANDLER========>"
  451. + ResultParser.parseResult(rawResult).getType().toString());
  452. boolean fromLiveScan = barcode != null;
  453. if (fromLiveScan)
  454. {
  455. // historyManager.addHistoryItem(rawResult, resultHandler);
  456. // Then not from history, so beep/vibrate and we have an image to
  457. // draw on
  458. beepManager.playBeepSoundAndVibrate();
  459. // drawResultPoints(barcode, scaleFactor, rawResult);
  460. }
  461. Intent result = new Intent();
  462. result.putExtra("pid", rawResult.getText());
  463. setResult(Activity.RESULT_OK, result);
  464. finish();
  465. // restartPreviewAfterDelay(1000l);
  466. // finish();
  467. //
  468. // switch (source) {
  469. // case NATIVE_APP_INTENT:
  470. // case PRODUCT_SEARCH_LINK:
  471. // handleDecodeExternally(rawResult, resultHandler, barcode);
  472. // break;
  473. // case ZXING_LINK:
  474. // if (scanFromWebPageManager == null ||
  475. // !scanFromWebPageManager.isScanFromWebPage()) {
  476. // handleDecodeInternally(rawResult, resultHandler, barcode);
  477. // } else {
  478. // handleDecodeExternally(rawResult, resultHandler, barcode);
  479. // }
  480. // break;
  481. // case NONE:
  482. // SharedPreferences prefs =
  483. // PreferenceManager.getDefaultSharedPreferences(this);
  484. // if (fromLiveScan &&
  485. // prefs.getBoolean(PreferencesActivity.KEY_BULK_MODE, false)) {
  486. // Toast.makeText(getApplicationContext(),
  487. // getResources().getString(R.string.msg_bulk_mode_scanned) + " (" +
  488. // rawResult.getText() + ')',
  489. // Toast.LENGTH_SHORT).show();
  490. // // Wait a moment or else it will scan the same barcode continuously
  491. // about 3 times
  492. // restartPreviewAfterDelay(BULK_MODE_SCAN_DELAY_MS);
  493. // } else {
  494. // handleDecodeInternally(rawResult, resultHandler, barcode);
  495. // }
  496. // break;
  497. // }
  498. }
  499. /**
  500. * Superimpose a line for 1D or dots for 2D to highlight the key features of
  501. * the barcode.
  502. *
  503. * @param barcode
  504. * A bitmap of the captured image.
  505. * @param scaleFactor
  506. * amount by which thumbnail was scaled
  507. * @param rawResult
  508. * The decoded results which contains the points to draw.
  509. */
  510. // private void drawResultPoints(Bitmap barcode, float scaleFactor,
  511. // Result rawResult)
  512. // {
  513. // ResultPoint[] points = rawResult.getResultPoints();
  514. // if (points != null && points.length > 0)
  515. // {
  516. // Canvas canvas = new Canvas(barcode);
  517. // Paint paint = new Paint();
  518. // paint.setColor(getResources().getColor(R.color.result_points));
  519. // if (points.length == 2)
  520. // {
  521. // paint.setStrokeWidth(4.0f);
  522. // drawLine(canvas, paint, points[0], points[1], scaleFactor);
  523. // }
  524. // else if (points.length == 4
  525. // && (rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A || rawResult
  526. // .getBarcodeFormat() == BarcodeFormat.EAN_13))
  527. // {
  528. // // Hacky special case -- draw two lines, for the barcode and
  529. // // metadata
  530. // drawLine(canvas, paint, points[0], points[1], scaleFactor);
  531. // drawLine(canvas, paint, points[2], points[3], scaleFactor);
  532. // }
  533. // else
  534. // {
  535. // paint.setStrokeWidth(10.0f);
  536. // for (ResultPoint point : points)
  537. // {
  538. // if (point != null)
  539. // {
  540. // canvas.drawPoint(scaleFactor * point.getX(),
  541. // scaleFactor * point.getY(), paint);
  542. // }
  543. // }
  544. // }
  545. // }
  546. // }
  547. private static void drawLine(Canvas canvas, Paint paint, ResultPoint a,
  548. ResultPoint b, float scaleFactor)
  549. {
  550. if (a != null && b != null)
  551. {
  552. canvas.drawLine(scaleFactor * a.getX(), scaleFactor * a.getY(),
  553. scaleFactor * b.getX(), scaleFactor * b.getY(), paint);
  554. }
  555. }
  556. // Put up our own UI for how to handle the decoded contents.
  557. // private void handleDecodeInternally(Result rawResult, ResultHandler
  558. // resultHandler, Bitmap barcode) {
  559. // statusView.setVisibility(View.GONE);
  560. // viewfinderView.setVisibility(View.GONE);
  561. // // resultView.setVisibility(View.VISIBLE);
  562. // Log.i(TAG, "RESULT=========>"+rawResult.getText().toString());
  563. // Log.i(TAG, "HANDLER========>"+resultHandler.getType().toString());
  564. // ImageView barcodeImageView = (ImageView)
  565. // findViewById(R.id.barcode_image_view);
  566. // if (barcode == null) {
  567. // barcodeImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(),
  568. // R.drawable.ic_launcher));
  569. // } else {
  570. // barcodeImageView.setImageBitmap(barcode);
  571. // }
  572. //
  573. // TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
  574. // formatTextView.setText(rawResult.getBarcodeFormat().toString());
  575. //
  576. // TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
  577. // typeTextView.setText(resultHandler.getType().toString());
  578. //
  579. // DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT,
  580. // DateFormat.SHORT);
  581. // TextView timeTextView = (TextView) findViewById(R.id.time_text_view);
  582. // timeTextView.setText(formatter.format(new
  583. // Date(rawResult.getTimestamp())));
  584. //
  585. //
  586. // TextView metaTextView = (TextView) findViewById(R.id.meta_text_view);
  587. // View metaTextViewLabel = findViewById(R.id.meta_text_view_label);
  588. // metaTextView.setVisibility(View.GONE);
  589. // metaTextViewLabel.setVisibility(View.GONE);
  590. // Map<ResultMetadataType,Object> metadata = rawResult.getResultMetadata();
  591. // if (metadata != null) {
  592. // StringBuilder metadataText = new StringBuilder(20);
  593. // for (Map.Entry<ResultMetadataType,Object> entry : metadata.entrySet()) {
  594. // if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) {
  595. // metadataText.append(entry.getValue()).append('\n');
  596. // }
  597. // }
  598. // if (metadataText.length() > 0) {
  599. // metadataText.setLength(metadataText.length() - 1);
  600. // metaTextView.setText(metadataText);
  601. // metaTextView.setVisibility(View.VISIBLE);
  602. // metaTextViewLabel.setVisibility(View.VISIBLE);
  603. // }
  604. // }
  605. //
  606. // TextView contentsTextView = (TextView)
  607. // findViewById(R.id.contents_text_view);
  608. // CharSequence displayContents = resultHandler.getDisplayContents();
  609. // contentsTextView.setText(displayContents);
  610. // // Crudely scale betweeen 22 and 32 -- bigger font for shorter text
  611. // int scaledSize = Math.max(22, 32 - displayContents.length() / 4);
  612. // contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);
  613. //
  614. // TextView supplementTextView = (TextView)
  615. // findViewById(R.id.contents_supplement_text_view);
  616. // supplementTextView.setText("");
  617. // supplementTextView.setOnClickListener(null);
  618. // // if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
  619. // // PreferencesActivity.KEY_SUPPLEMENTAL, true)) {
  620. // // SupplementalInfoRetriever.maybeInvokeRetrieval(supplementTextView,
  621. // // resultHandler.getResult(),
  622. // // historyManager,
  623. // // this);
  624. // // }
  625. //
  626. // int buttonCount = resultHandler.getButtonCount();
  627. // ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
  628. // buttonView.requestFocus();
  629. // for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
  630. // TextView button = (TextView) buttonView.getChildAt(x);
  631. // if (x < buttonCount) {
  632. // button.setVisibility(View.VISIBLE);
  633. // button.setText(resultHandler.getButtonText(x));
  634. // button.setOnClickListener(new ResultButtonListener(resultHandler, x));
  635. // } else {
  636. // button.setVisibility(View.GONE);
  637. // }
  638. // }
  639. //
  640. // if (copyToClipboard && !resultHandler.areContentsSecure()) {
  641. // ClipboardInterface.setText(displayContents, this);
  642. // }
  643. // }
  644. // // Briefly show the contents of the barcode, then handle the result
  645. // outside Barcode Scanner.
  646. // private void handleDecodeExternally(Result rawResult, ResultHandler
  647. // resultHandler, Bitmap barcode) {
  648. //
  649. // if (barcode != null) {
  650. // viewfinderView.drawResultBitmap(barcode);
  651. // }
  652. //
  653. // long resultDurationMS;
  654. // if (getIntent() == null) {
  655. // resultDurationMS = DEFAULT_INTENT_RESULT_DURATION_MS;
  656. // } else {
  657. // resultDurationMS =
  658. // getIntent().getLongExtra(Intents.Scan.RESULT_DISPLAY_DURATION_MS,
  659. // DEFAULT_INTENT_RESULT_DURATION_MS);
  660. // }
  661. //
  662. // if (resultDurationMS > 0) {
  663. // String rawResultString = String.valueOf(rawResult);
  664. // if (rawResultString.length() > 32) {
  665. // rawResultString = rawResultString.substring(0, 32) + " ...";
  666. // }
  667. // statusView.setText(getString(resultHandler.getDisplayTitle()) + " : " +
  668. // rawResultString);
  669. // }
  670. //
  671. // if (copyToClipboard && !resultHandler.areContentsSecure()) {
  672. // CharSequence text = resultHandler.getDisplayContents();
  673. // ClipboardInterface.setText(text, this);
  674. // }
  675. //
  676. // if (source == IntentSource.NATIVE_APP_INTENT) {
  677. //
  678. // // Hand back whatever action they requested - this can be changed to
  679. // Intents.Scan.ACTION when
  680. // // the deprecated intent is retired.
  681. // Intent intent = new Intent(getIntent().getAction());
  682. // intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
  683. // intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
  684. // intent.putExtra(Intents.Scan.RESULT_FORMAT,
  685. // rawResult.getBarcodeFormat().toString());
  686. // byte[] rawBytes = rawResult.getRawBytes();
  687. // if (rawBytes != null && rawBytes.length > 0) {
  688. // intent.putExtra(Intents.Scan.RESULT_BYTES, rawBytes);
  689. // }
  690. // Map<ResultMetadataType,?> metadata = rawResult.getResultMetadata();
  691. // if (metadata != null) {
  692. // if (metadata.containsKey(ResultMetadataType.UPC_EAN_EXTENSION)) {
  693. // intent.putExtra(Intents.Scan.RESULT_UPC_EAN_EXTENSION,
  694. // metadata.get(ResultMetadataType.UPC_EAN_EXTENSION).toString());
  695. // }
  696. // Number orientation = (Number)
  697. // metadata.get(ResultMetadataType.ORIENTATION);
  698. // if (orientation != null) {
  699. // intent.putExtra(Intents.Scan.RESULT_ORIENTATION, orientation.intValue());
  700. // }
  701. // String ecLevel = (String)
  702. // metadata.get(ResultMetadataType.ERROR_CORRECTION_LEVEL);
  703. // if (ecLevel != null) {
  704. // intent.putExtra(Intents.Scan.RESULT_ERROR_CORRECTION_LEVEL, ecLevel);
  705. // }
  706. // @SuppressWarnings("unchecked")
  707. // Iterable<byte[]> byteSegments = (Iterable<byte[]>)
  708. // metadata.get(ResultMetadataType.BYTE_SEGMENTS);
  709. // if (byteSegments != null) {
  710. // int i = 0;
  711. // for (byte[] byteSegment : byteSegments) {
  712. // intent.putExtra(Intents.Scan.RESULT_BYTE_SEGMENTS_PREFIX + i,
  713. // byteSegment);
  714. // i++;
  715. // }
  716. // }
  717. // }
  718. // sendReplyMessage(R.id.return_scan_result, intent, resultDurationMS);
  719. //
  720. // } else if (source == IntentSource.PRODUCT_SEARCH_LINK) {
  721. //
  722. // // Reformulate the URL which triggered us into a query, so that the
  723. // request goes to the same
  724. // // TLD as the scan URL.
  725. // int end = sourceUrl.lastIndexOf("/scan");
  726. // String replyURL = sourceUrl.substring(0, end) + "?q=" +
  727. // resultHandler.getDisplayContents() + "&source=zxing";
  728. // sendReplyMessage(R.id.launch_product_query, replyURL, resultDurationMS);
  729. //
  730. // } else if (source == IntentSource.ZXING_LINK) {
  731. //
  732. // if (scanFromWebPageManager != null &&
  733. // scanFromWebPageManager.isScanFromWebPage()) {
  734. // String replyURL = scanFromWebPageManager.buildReplyURL(rawResult,
  735. // resultHandler);
  736. // sendReplyMessage(R.id.launch_product_query, replyURL, resultDurationMS);
  737. // }
  738. //
  739. // }
  740. // }
  741. // private void sendReplyMessage(int id, Object arg, long delayMS) {
  742. // if (handler != null) {
  743. // Message message = Message.obtain(handler, id, arg);
  744. // if (delayMS > 0L) {
  745. // handler.sendMessageDelayed(message, delayMS);
  746. // } else {
  747. // handler.sendMessage(message);
  748. // }
  749. // }
  750. // }
  751. private void initCamera(SurfaceHolder surfaceHolder)
  752. {
  753. if (surfaceHolder == null)
  754. {
  755. throw new IllegalStateException("No SurfaceHolder provided");
  756. }
  757. if (cameraManager.isOpen())
  758. {
  759. Log.w(TAG,
  760. "initCamera() while already open -- late SurfaceView callback?");
  761. return;
  762. }
  763. try
  764. {
  765. cameraManager.openDriver(surfaceHolder);
  766. // Creating the handler starts the preview, which can also throw a
  767. // RuntimeException.
  768. if (handler == null)
  769. {
  770. handler = new CaptureActivityHandler(this, decodeFormats,
  771. decodeHints, characterSet, cameraManager);
  772. }
  773. decodeOrStoreSavedBitmap(null, null);
  774. }
  775. catch (IOException ioe)
  776. {
  777. Log.w(TAG, ioe);
  778. displayFrameworkBugMessageAndExit();
  779. }
  780. catch (RuntimeException e)
  781. {
  782. // Barcode Scanner has seen crashes in the wild of this variety:
  783. // java.?lang.?RuntimeException: Fail to connect to camera service
  784. Log.w(TAG, "Unexpected error initializing camera", e);
  785. displayFrameworkBugMessageAndExit();
  786. }
  787. }
  788. private void displayFrameworkBugMessageAndExit()
  789. {
  790. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  791. builder.setTitle(getString(R.string.app_name));
  792. builder.setMessage(getString(R.string.msg_camera_framework_bug));
  793. builder.setPositiveButton(R.string.button_ok, new FinishListener(this));
  794. builder.setOnCancelListener(new FinishListener(this));
  795. builder.show();
  796. }
  797. public void restartPreviewAfterDelay(long delayMS)
  798. {
  799. if (handler != null)
  800. {
  801. handler.sendEmptyMessageDelayed(R.id.decode_failed, delayMS);
  802. }
  803. resetStatusView();
  804. }
  805. private void resetStatusView()
  806. {
  807. // resultView.setVisibility(View.GONE);
  808. statusView.setText(R.string.msg_default_status);
  809. statusView.setVisibility(View.VISIBLE);
  810. viewfinderView.setVisibility(View.VISIBLE);
  811. lastResult = null;
  812. }
  813. public void drawViewfinder()
  814. {
  815. viewfinderView.drawViewfinder();
  816. }
  817. }