CaptureActivity.java 26 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.e(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. @Override
  335. public boolean onOptionsItemSelected(MenuItem item)
  336. {
  337. Intent intent = new Intent(Intent.ACTION_VIEW);
  338. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
  339. switch (item.getItemId())
  340. {
  341. // case R.id.menu_share:
  342. // intent.setClassName(this, ShareActivity.class.getName());
  343. // startActivity(intent);
  344. // break;
  345. // case R.id.menu_history:
  346. // intent.setClassName(this, HistoryActivity.class.getName());
  347. // startActivityForResult(intent, HISTORY_REQUEST_CODE);
  348. // break;
  349. case R.id.menu_settings:
  350. intent.setClassName(this, PreferencesActivity.class.getName());
  351. startActivity(intent);
  352. break;
  353. // case R.id.menu_help:
  354. // intent.setClassName(this, HelpActivity.class.getName());
  355. // startActivity(intent);
  356. // break;
  357. default:
  358. return super.onOptionsItemSelected(item);
  359. }
  360. return true;
  361. }
  362. // @Override
  363. // public void onActivityResult(int requestCode, int resultCode, Intent
  364. // intent) {
  365. // if (resultCode == RESULT_OK) {
  366. // // if (requestCode == HISTORY_REQUEST_CODE)
  367. // // {
  368. // // int itemNumber = intent.getIntExtra(Intents.History.ITEM_NUMBER, -1);
  369. // // if (itemNumber >= 0) {
  370. // // HistoryItem historyItem = historyManager.buildHistoryItem(itemNumber);
  371. // // decodeOrStoreSavedBitmap(null, historyItem.getResult());
  372. // // }
  373. // // }
  374. // }
  375. // }
  376. private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result)
  377. {
  378. // Bitmap isn't used yet -- will be used soon
  379. if (handler == null)
  380. {
  381. savedResultToShow = result;
  382. }
  383. else
  384. {
  385. if (result != null)
  386. {
  387. savedResultToShow = result;
  388. }
  389. if (savedResultToShow != null)
  390. {
  391. Message message = Message.obtain(handler,
  392. R.id.decode_succeeded, savedResultToShow);
  393. handler.sendMessage(message);
  394. }
  395. savedResultToShow = null;
  396. }
  397. }
  398. @Override
  399. public void surfaceCreated(SurfaceHolder holder)
  400. {
  401. if (holder == null)
  402. {
  403. Log.e(TAG,
  404. "*** WARNING *** surfaceCreated() gave us a null surface!");
  405. }
  406. if (!hasSurface)
  407. {
  408. hasSurface = true;
  409. initCamera(holder);
  410. }
  411. }
  412. @Override
  413. public void surfaceDestroyed(SurfaceHolder holder)
  414. {
  415. hasSurface = false;
  416. }
  417. @Override
  418. public void surfaceChanged(SurfaceHolder holder, int format, int width,
  419. int height)
  420. {
  421. }
  422. /**
  423. * A valid barcode has been found, so give an indication of success and show
  424. * the results.
  425. *
  426. * @param rawResult
  427. * The contents of the barcode.
  428. * @param scaleFactor
  429. * amount by which thumbnail was scaled
  430. * @param barcode
  431. * A greyscale bitmap of the camera data which was decoded.
  432. */
  433. public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor)
  434. {
  435. String tag = swith_button.getTag().toString();
  436. if (Boolean.parseBoolean(tag) == false)
  437. {
  438. restartPreviewAfterDelay(0L);
  439. return;
  440. }
  441. inactivityTimer.onActivity();
  442. lastResult = rawResult;
  443. TextView debugTextView = (TextView) findViewById(R.id.textView1);
  444. debugTextView.setText(rawResult.getText());
  445. // ResultHandler resultHandler =
  446. // ResultHandlerFactory.makeResultHandler(this, rawResult);
  447. Log.i(TAG, "RESULT=========>" + rawResult.getText().toString());
  448. // ParsedResult result = parseResult(rawResult);
  449. Log.i(TAG, "HANDLER========>"
  450. + ResultParser.parseResult(rawResult).getType().toString());
  451. boolean fromLiveScan = barcode != null;
  452. if (fromLiveScan)
  453. {
  454. // historyManager.addHistoryItem(rawResult, resultHandler);
  455. // Then not from history, so beep/vibrate and we have an image to
  456. // draw on
  457. beepManager.playBeepSoundAndVibrate();
  458. // drawResultPoints(barcode, scaleFactor, rawResult);
  459. }
  460. Intent result = new Intent();
  461. result.putExtra("pid", rawResult.getText());
  462. setResult(Activity.RESULT_OK, result);
  463. finish();
  464. // restartPreviewAfterDelay(1000l);
  465. // finish();
  466. //
  467. // switch (source) {
  468. // case NATIVE_APP_INTENT:
  469. // case PRODUCT_SEARCH_LINK:
  470. // handleDecodeExternally(rawResult, resultHandler, barcode);
  471. // break;
  472. // case ZXING_LINK:
  473. // if (scanFromWebPageManager == null ||
  474. // !scanFromWebPageManager.isScanFromWebPage()) {
  475. // handleDecodeInternally(rawResult, resultHandler, barcode);
  476. // } else {
  477. // handleDecodeExternally(rawResult, resultHandler, barcode);
  478. // }
  479. // break;
  480. // case NONE:
  481. // SharedPreferences prefs =
  482. // PreferenceManager.getDefaultSharedPreferences(this);
  483. // if (fromLiveScan &&
  484. // prefs.getBoolean(PreferencesActivity.KEY_BULK_MODE, false)) {
  485. // Toast.makeText(getApplicationContext(),
  486. // getResources().getString(R.string.msg_bulk_mode_scanned) + " (" +
  487. // rawResult.getText() + ')',
  488. // Toast.LENGTH_SHORT).show();
  489. // // Wait a moment or else it will scan the same barcode continuously
  490. // about 3 times
  491. // restartPreviewAfterDelay(BULK_MODE_SCAN_DELAY_MS);
  492. // } else {
  493. // handleDecodeInternally(rawResult, resultHandler, barcode);
  494. // }
  495. // break;
  496. // }
  497. }
  498. /**
  499. * Superimpose a line for 1D or dots for 2D to highlight the key features of
  500. * the barcode.
  501. *
  502. * @param barcode
  503. * A bitmap of the captured image.
  504. * @param scaleFactor
  505. * amount by which thumbnail was scaled
  506. * @param rawResult
  507. * The decoded results which contains the points to draw.
  508. */
  509. // private void drawResultPoints(Bitmap barcode, float scaleFactor,
  510. // Result rawResult)
  511. // {
  512. // ResultPoint[] points = rawResult.getResultPoints();
  513. // if (points != null && points.length > 0)
  514. // {
  515. // Canvas canvas = new Canvas(barcode);
  516. // Paint paint = new Paint();
  517. // paint.setColor(getResources().getColor(R.color.result_points));
  518. // if (points.length == 2)
  519. // {
  520. // paint.setStrokeWidth(4.0f);
  521. // drawLine(canvas, paint, points[0], points[1], scaleFactor);
  522. // }
  523. // else if (points.length == 4
  524. // && (rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A || rawResult
  525. // .getBarcodeFormat() == BarcodeFormat.EAN_13))
  526. // {
  527. // // Hacky special case -- draw two lines, for the barcode and
  528. // // metadata
  529. // drawLine(canvas, paint, points[0], points[1], scaleFactor);
  530. // drawLine(canvas, paint, points[2], points[3], scaleFactor);
  531. // }
  532. // else
  533. // {
  534. // paint.setStrokeWidth(10.0f);
  535. // for (ResultPoint point : points)
  536. // {
  537. // if (point != null)
  538. // {
  539. // canvas.drawPoint(scaleFactor * point.getX(),
  540. // scaleFactor * point.getY(), paint);
  541. // }
  542. // }
  543. // }
  544. // }
  545. // }
  546. private static void drawLine(Canvas canvas, Paint paint, ResultPoint a,
  547. ResultPoint b, float scaleFactor)
  548. {
  549. if (a != null && b != null)
  550. {
  551. canvas.drawLine(scaleFactor * a.getX(), scaleFactor * a.getY(),
  552. scaleFactor * b.getX(), scaleFactor * b.getY(), paint);
  553. }
  554. }
  555. // Put up our own UI for how to handle the decoded contents.
  556. // private void handleDecodeInternally(Result rawResult, ResultHandler
  557. // resultHandler, Bitmap barcode) {
  558. // statusView.setVisibility(View.GONE);
  559. // viewfinderView.setVisibility(View.GONE);
  560. // // resultView.setVisibility(View.VISIBLE);
  561. // Log.i(TAG, "RESULT=========>"+rawResult.getText().toString());
  562. // Log.i(TAG, "HANDLER========>"+resultHandler.getType().toString());
  563. // ImageView barcodeImageView = (ImageView)
  564. // findViewById(R.id.barcode_image_view);
  565. // if (barcode == null) {
  566. // barcodeImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(),
  567. // R.drawable.ic_launcher));
  568. // } else {
  569. // barcodeImageView.setImageBitmap(barcode);
  570. // }
  571. //
  572. // TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
  573. // formatTextView.setText(rawResult.getBarcodeFormat().toString());
  574. //
  575. // TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
  576. // typeTextView.setText(resultHandler.getType().toString());
  577. //
  578. // DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT,
  579. // DateFormat.SHORT);
  580. // TextView timeTextView = (TextView) findViewById(R.id.time_text_view);
  581. // timeTextView.setText(formatter.format(new
  582. // Date(rawResult.getTimestamp())));
  583. //
  584. //
  585. // TextView metaTextView = (TextView) findViewById(R.id.meta_text_view);
  586. // View metaTextViewLabel = findViewById(R.id.meta_text_view_label);
  587. // metaTextView.setVisibility(View.GONE);
  588. // metaTextViewLabel.setVisibility(View.GONE);
  589. // Map<ResultMetadataType,Object> metadata = rawResult.getResultMetadata();
  590. // if (metadata != null) {
  591. // StringBuilder metadataText = new StringBuilder(20);
  592. // for (Map.Entry<ResultMetadataType,Object> entry : metadata.entrySet()) {
  593. // if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) {
  594. // metadataText.append(entry.getValue()).append('\n');
  595. // }
  596. // }
  597. // if (metadataText.length() > 0) {
  598. // metadataText.setLength(metadataText.length() - 1);
  599. // metaTextView.setText(metadataText);
  600. // metaTextView.setVisibility(View.VISIBLE);
  601. // metaTextViewLabel.setVisibility(View.VISIBLE);
  602. // }
  603. // }
  604. //
  605. // TextView contentsTextView = (TextView)
  606. // findViewById(R.id.contents_text_view);
  607. // CharSequence displayContents = resultHandler.getDisplayContents();
  608. // contentsTextView.setText(displayContents);
  609. // // Crudely scale betweeen 22 and 32 -- bigger font for shorter text
  610. // int scaledSize = Math.max(22, 32 - displayContents.length() / 4);
  611. // contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);
  612. //
  613. // TextView supplementTextView = (TextView)
  614. // findViewById(R.id.contents_supplement_text_view);
  615. // supplementTextView.setText("");
  616. // supplementTextView.setOnClickListener(null);
  617. // // if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
  618. // // PreferencesActivity.KEY_SUPPLEMENTAL, true)) {
  619. // // SupplementalInfoRetriever.maybeInvokeRetrieval(supplementTextView,
  620. // // resultHandler.getResult(),
  621. // // historyManager,
  622. // // this);
  623. // // }
  624. //
  625. // int buttonCount = resultHandler.getButtonCount();
  626. // ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
  627. // buttonView.requestFocus();
  628. // for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
  629. // TextView button = (TextView) buttonView.getChildAt(x);
  630. // if (x < buttonCount) {
  631. // button.setVisibility(View.VISIBLE);
  632. // button.setText(resultHandler.getButtonText(x));
  633. // button.setOnClickListener(new ResultButtonListener(resultHandler, x));
  634. // } else {
  635. // button.setVisibility(View.GONE);
  636. // }
  637. // }
  638. //
  639. // if (copyToClipboard && !resultHandler.areContentsSecure()) {
  640. // ClipboardInterface.setText(displayContents, this);
  641. // }
  642. // }
  643. // // Briefly show the contents of the barcode, then handle the result
  644. // outside Barcode Scanner.
  645. // private void handleDecodeExternally(Result rawResult, ResultHandler
  646. // resultHandler, Bitmap barcode) {
  647. //
  648. // if (barcode != null) {
  649. // viewfinderView.drawResultBitmap(barcode);
  650. // }
  651. //
  652. // long resultDurationMS;
  653. // if (getIntent() == null) {
  654. // resultDurationMS = DEFAULT_INTENT_RESULT_DURATION_MS;
  655. // } else {
  656. // resultDurationMS =
  657. // getIntent().getLongExtra(Intents.Scan.RESULT_DISPLAY_DURATION_MS,
  658. // DEFAULT_INTENT_RESULT_DURATION_MS);
  659. // }
  660. //
  661. // if (resultDurationMS > 0) {
  662. // String rawResultString = String.valueOf(rawResult);
  663. // if (rawResultString.length() > 32) {
  664. // rawResultString = rawResultString.substring(0, 32) + " ...";
  665. // }
  666. // statusView.setText(getString(resultHandler.getDisplayTitle()) + " : " +
  667. // rawResultString);
  668. // }
  669. //
  670. // if (copyToClipboard && !resultHandler.areContentsSecure()) {
  671. // CharSequence text = resultHandler.getDisplayContents();
  672. // ClipboardInterface.setText(text, this);
  673. // }
  674. //
  675. // if (source == IntentSource.NATIVE_APP_INTENT) {
  676. //
  677. // // Hand back whatever action they requested - this can be changed to
  678. // Intents.Scan.ACTION when
  679. // // the deprecated intent is retired.
  680. // Intent intent = new Intent(getIntent().getAction());
  681. // intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
  682. // intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
  683. // intent.putExtra(Intents.Scan.RESULT_FORMAT,
  684. // rawResult.getBarcodeFormat().toString());
  685. // byte[] rawBytes = rawResult.getRawBytes();
  686. // if (rawBytes != null && rawBytes.length > 0) {
  687. // intent.putExtra(Intents.Scan.RESULT_BYTES, rawBytes);
  688. // }
  689. // Map<ResultMetadataType,?> metadata = rawResult.getResultMetadata();
  690. // if (metadata != null) {
  691. // if (metadata.containsKey(ResultMetadataType.UPC_EAN_EXTENSION)) {
  692. // intent.putExtra(Intents.Scan.RESULT_UPC_EAN_EXTENSION,
  693. // metadata.get(ResultMetadataType.UPC_EAN_EXTENSION).toString());
  694. // }
  695. // Number orientation = (Number)
  696. // metadata.get(ResultMetadataType.ORIENTATION);
  697. // if (orientation != null) {
  698. // intent.putExtra(Intents.Scan.RESULT_ORIENTATION, orientation.intValue());
  699. // }
  700. // String ecLevel = (String)
  701. // metadata.get(ResultMetadataType.ERROR_CORRECTION_LEVEL);
  702. // if (ecLevel != null) {
  703. // intent.putExtra(Intents.Scan.RESULT_ERROR_CORRECTION_LEVEL, ecLevel);
  704. // }
  705. // @SuppressWarnings("unchecked")
  706. // Iterable<byte[]> byteSegments = (Iterable<byte[]>)
  707. // metadata.get(ResultMetadataType.BYTE_SEGMENTS);
  708. // if (byteSegments != null) {
  709. // int i = 0;
  710. // for (byte[] byteSegment : byteSegments) {
  711. // intent.putExtra(Intents.Scan.RESULT_BYTE_SEGMENTS_PREFIX + i,
  712. // byteSegment);
  713. // i++;
  714. // }
  715. // }
  716. // }
  717. // sendReplyMessage(R.id.return_scan_result, intent, resultDurationMS);
  718. //
  719. // } else if (source == IntentSource.PRODUCT_SEARCH_LINK) {
  720. //
  721. // // Reformulate the URL which triggered us into a query, so that the
  722. // request goes to the same
  723. // // TLD as the scan URL.
  724. // int end = sourceUrl.lastIndexOf("/scan");
  725. // String replyURL = sourceUrl.substring(0, end) + "?q=" +
  726. // resultHandler.getDisplayContents() + "&source=zxing";
  727. // sendReplyMessage(R.id.launch_product_query, replyURL, resultDurationMS);
  728. //
  729. // } else if (source == IntentSource.ZXING_LINK) {
  730. //
  731. // if (scanFromWebPageManager != null &&
  732. // scanFromWebPageManager.isScanFromWebPage()) {
  733. // String replyURL = scanFromWebPageManager.buildReplyURL(rawResult,
  734. // resultHandler);
  735. // sendReplyMessage(R.id.launch_product_query, replyURL, resultDurationMS);
  736. // }
  737. //
  738. // }
  739. // }
  740. // private void sendReplyMessage(int id, Object arg, long delayMS) {
  741. // if (handler != null) {
  742. // Message message = Message.obtain(handler, id, arg);
  743. // if (delayMS > 0L) {
  744. // handler.sendMessageDelayed(message, delayMS);
  745. // } else {
  746. // handler.sendMessage(message);
  747. // }
  748. // }
  749. // }
  750. private void initCamera(SurfaceHolder surfaceHolder)
  751. {
  752. if (surfaceHolder == null)
  753. {
  754. throw new IllegalStateException("No SurfaceHolder provided");
  755. }
  756. if (cameraManager.isOpen())
  757. {
  758. Log.w(TAG,
  759. "initCamera() while already open -- late SurfaceView callback?");
  760. return;
  761. }
  762. try
  763. {
  764. cameraManager.openDriver(surfaceHolder);
  765. // Creating the handler starts the preview, which can also throw a
  766. // RuntimeException.
  767. if (handler == null)
  768. {
  769. handler = new CaptureActivityHandler(this, decodeFormats,
  770. decodeHints, characterSet, cameraManager);
  771. }
  772. decodeOrStoreSavedBitmap(null, null);
  773. }
  774. catch (IOException ioe)
  775. {
  776. Log.w(TAG, ioe);
  777. displayFrameworkBugMessageAndExit();
  778. }
  779. catch (RuntimeException e)
  780. {
  781. // Barcode Scanner has seen crashes in the wild of this variety:
  782. // java.?lang.?RuntimeException: Fail to connect to camera service
  783. Log.w(TAG, "Unexpected error initializing camera", e);
  784. displayFrameworkBugMessageAndExit();
  785. }
  786. }
  787. private void displayFrameworkBugMessageAndExit()
  788. {
  789. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  790. builder.setTitle(getString(R.string.app_name));
  791. builder.setMessage(getString(R.string.msg_camera_framework_bug));
  792. builder.setPositiveButton(R.string.button_ok, new FinishListener(this));
  793. builder.setOnCancelListener(new FinishListener(this));
  794. builder.show();
  795. }
  796. public void restartPreviewAfterDelay(long delayMS)
  797. {
  798. if (handler != null)
  799. {
  800. handler.sendEmptyMessageDelayed(R.id.decode_failed, delayMS);
  801. }
  802. resetStatusView();
  803. }
  804. private void resetStatusView()
  805. {
  806. // resultView.setVisibility(View.GONE);
  807. statusView.setText(R.string.msg_default_status);
  808. statusView.setVisibility(View.VISIBLE);
  809. viewfinderView.setVisibility(View.VISIBLE);
  810. lastResult = null;
  811. }
  812. public void drawViewfinder()
  813. {
  814. viewfinderView.drawViewfinder();
  815. }
  816. }