Guest User

Untitled

a guest
Feb 9th, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.02 KB | None | 0 0
  1. package com.example.fs.barcodescanner;
  2.  
  3. import android.Manifest;
  4. import android.annotation.SuppressLint;
  5. import android.app.Activity;
  6. import android.app.AlertDialog;
  7. import android.app.Dialog;
  8. import android.content.Context;
  9. import android.content.DialogInterface;
  10. import android.content.Intent;
  11. import android.content.IntentFilter;
  12. import android.content.pm.PackageManager;
  13. import android.hardware.Camera;
  14. import android.os.Build;
  15. import android.os.Bundle;
  16. import android.support.annotation.NonNull;
  17. import android.support.design.widget.Snackbar;
  18. import android.support.v4.app.ActivityCompat;
  19. import android.support.v7.app.AppCompatActivity;
  20. import android.util.Log;
  21. import android.view.GestureDetector;
  22. import android.view.MotionEvent;
  23. import android.view.ScaleGestureDetector;
  24. import android.view.View;
  25. import android.view.WindowId;
  26. import android.widget.Toast;
  27.  
  28. import com.example.fs.barcodescanner.ui.camera.CameraSource;
  29. import com.example.fs.barcodescanner.ui.camera.CameraSourcePreview;
  30. import com.example.fs.barcodescanner.ui.camera.GraphicOverlay;
  31. import com.google.android.gms.common.ConnectionResult;
  32. import com.google.android.gms.common.GoogleApiAvailability;
  33. import com.google.android.gms.common.api.CommonStatusCodes;
  34. import com.google.android.gms.vision.MultiProcessor;
  35. import com.google.android.gms.vision.barcode.Barcode;
  36. import com.google.android.gms.vision.barcode.BarcodeDetector;
  37.  
  38. import java.io.IOException;
  39.  
  40. public final class BarcodeCaptureActivity extends AppCompatActivity {
  41. private static final String TAG = "Barcode-reader";
  42.  
  43. // intent request code to handle updating play services if needed.
  44. private static final int RC_HANDLE_GMS = 9001;
  45.  
  46. // permission request codes need to be < 256
  47. private static final int RC_HANDLE_CAMERA_PERM = 2;
  48.  
  49. // constants used to pass extra data in the intent
  50. public static final String AutoFocus = "AutoFocus";
  51. public static final String UseFlash = "UseFlash";
  52. public static final String BarcodeObject = "Barcode";
  53.  
  54. private CameraSource mCameraSource;
  55. private CameraSourcePreview mPreview;
  56. private GraphicOverlay<BarcodeGraphic> mGraphicOverlay;
  57.  
  58. // helper objects for detecting taps and pinches.
  59. private ScaleGestureDetector scaleGestureDetector;
  60. private GestureDetector gestureDetector;
  61. private WindowId.FocusObserver fo;
  62.  
  63. /**
  64. * Initializes the UI and creates the detector pipeline.
  65. */
  66. @Override
  67. public void onCreate(Bundle icicle) {
  68. super.onCreate(icicle);
  69. setContentView(R.layout.activity_barcode_capture);
  70.  
  71. mPreview = (CameraSourcePreview) findViewById(R.id.preview);
  72. mGraphicOverlay = (GraphicOverlay<BarcodeGraphic>) findViewById(R.id.graphicOverlay);
  73.  
  74. // read parameters from the intent used to launch the activity.
  75. boolean autoFocus = getIntent().getBooleanExtra(AutoFocus, false);
  76. boolean useFlash = getIntent().getBooleanExtra(UseFlash, false);
  77.  
  78. // Check for the camera permission before accessing the camera. If the
  79. // permission is not granted yet, request permission.
  80. int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
  81. if (rc == PackageManager.PERMISSION_GRANTED) {
  82. createCameraSource(autoFocus, useFlash);
  83. } else {
  84. requestCameraPermission();
  85. }
  86.  
  87. gestureDetector = new GestureDetector(this, new CaptureGestureListener());
  88. scaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());
  89.  
  90. Snackbar.make(mGraphicOverlay, "Tap to capture. Pinch/Stretch to zoom",
  91. Snackbar.LENGTH_LONG)
  92. .show();
  93. }
  94.  
  95. /**
  96. * Handles the requesting of the camera permission. This includes
  97. * showing a "Snackbar" message of why the permission is needed then
  98. * sending the request.
  99. */
  100. private void requestCameraPermission() {
  101. Log.w(TAG, "Camera permission is not granted. Requesting permission");
  102.  
  103. final String[] permissions = new String[]{Manifest.permission.CAMERA};
  104.  
  105. if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
  106. Manifest.permission.CAMERA)) {
  107. ActivityCompat.requestPermissions(this, permissions, RC_HANDLE_CAMERA_PERM);
  108. return;
  109. }
  110.  
  111. final Activity thisActivity = this;
  112.  
  113. View.OnClickListener listener = new View.OnClickListener() {
  114. @Override
  115. public void onClick(View view) {
  116. ActivityCompat.requestPermissions(thisActivity, permissions,
  117. RC_HANDLE_CAMERA_PERM);
  118. }
  119. };
  120.  
  121. Snackbar.make(mGraphicOverlay, R.string.permission_camera_rationale,
  122. Snackbar.LENGTH_INDEFINITE)
  123. .setAction(R.string.ok, listener)
  124. .show();
  125. }
  126.  
  127. @Override
  128. public boolean onTouchEvent(MotionEvent e) {
  129. boolean b = scaleGestureDetector.onTouchEvent(e);
  130. System.out.println("scale gesture"+b);
  131. boolean c = gestureDetector.onTouchEvent(e);
  132. System.out.println("tap gesture"+c);
  133. return b || c || super.onTouchEvent(e);
  134. }
  135.  
  136.  
  137. /**
  138. * Creates and starts the camera. Note that this uses a higher resolution in comparison
  139. * to other detection examples to enable the barcode detector to detect small barcodes
  140. * at long distances.
  141. *
  142. * Suppressing InlinedApi since there is a check that the minimum version is met before using
  143. * the constant.
  144. */
  145. @SuppressLint("InlinedApi")
  146. private void createCameraSource(boolean autoFocus, boolean useFlash) {
  147. Context context = getApplicationContext();
  148.  
  149. // A barcode detector is created to track barcodes. An associated multi-processor instance
  150. // is set to receive the barcode detection results, track the barcodes, and maintain
  151. // graphics for each barcode on screen. The factory is used by the multi-processor to
  152. // create a separate tracker instance for each barcode.
  153. BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(context).build();
  154. BarcodeTrackerFactory barcodeFactory = new BarcodeTrackerFactory(mGraphicOverlay);
  155. barcodeDetector.setProcessor(
  156. new MultiProcessor.Builder<>(barcodeFactory).build());
  157.  
  158. if (!barcodeDetector.isOperational()) {
  159. // Note: The first time that an app using the barcode or face API is installed on a
  160. // device, GMS will download a native libraries to the device in order to do detection.
  161. // Usually this completes before the app is run for the first time. But if that
  162. // download has not yet completed, then the above call will not detect any barcodes
  163. // and/or faces.
  164. //
  165. // isOperational() can be used to check if the required native libraries are currently
  166. // available. The detectors will automatically become operational once the library
  167. // downloads complete on device.
  168. Log.w(TAG, "Detector dependencies are not yet available.");
  169.  
  170. // Check for low storage. If there is low storage, the native library will not be
  171. // downloaded, so detection will not become operational.
  172. IntentFilter lowstorageFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
  173. boolean hasLowStorage = registerReceiver(null, lowstorageFilter) != null;
  174.  
  175. if (hasLowStorage) {
  176. Toast.makeText(this, R.string.low_storage_error, Toast.LENGTH_LONG).show();
  177. Log.w(TAG, getString(R.string.low_storage_error));
  178. }
  179. }
  180.  
  181. // Creates and starts the camera. Note that this uses a higher resolution in comparison
  182. // to other detection examples to enable the barcode detector to detect small barcodes
  183. // at long distances.
  184. CameraSource.Builder builder = new CameraSource.Builder(getApplicationContext(), barcodeDetector)
  185. .setFacing(CameraSource.CAMERA_FACING_BACK)
  186. .setRequestedPreviewSize(1600, 1024)
  187. .setRequestedFps(15.0f);
  188.  
  189. // make sure that auto focus is an available option
  190. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
  191. builder = builder.setFocusMode(
  192. autoFocus ? Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE : null);
  193. }
  194.  
  195. mCameraSource = builder
  196. .setFlashMode(useFlash ? Camera.Parameters.FLASH_MODE_TORCH : null)
  197. .build();
  198. }
  199.  
  200. /**
  201. * Restarts the camera.
  202. */
  203. @Override
  204. protected void onResume() {
  205. super.onResume();
  206. startCameraSource();
  207. }
  208.  
  209. /**
  210. * Stops the camera.
  211. */
  212. @Override
  213. protected void onPause() {
  214. super.onPause();
  215. if (mPreview != null) {
  216. mPreview.stop();
  217. }
  218. }
  219.  
  220. /**
  221. * Releases the resources associated with the camera source, the associated detectors, and the
  222. * rest of the processing pipeline.
  223. */
  224. @Override
  225. protected void onDestroy() {
  226. super.onDestroy();
  227. if (mPreview != null) {
  228. mPreview.release();
  229. }
  230. }
  231.  
  232. /**
  233. * Callback for the result from requesting permissions. This method
  234. * is invoked for every call on {@link #requestPermissions(String[], int)}.
  235. * <p>
  236. * <strong>Note:</strong> It is possible that the permissions request interaction
  237. * with the user is interrupted. In this case you will receive empty permissions
  238. * and results arrays which should be treated as a cancellation.
  239. * </p>
  240. *
  241. * @param requestCode The request code passed in {@link #requestPermissions(String[], int)}.
  242. * @param permissions The requested permissions. Never null.
  243. * @param grantResults The grant results for the corresponding permissions
  244. * which is either {@link PackageManager#PERMISSION_GRANTED}
  245. * or {@link PackageManager#PERMISSION_DENIED}. Never null.
  246. * @see #requestPermissions(String[], int)
  247. */
  248. @Override
  249. public void onRequestPermissionsResult(int requestCode,
  250. @NonNull String[] permissions,
  251. @NonNull int[] grantResults) {
  252. if (requestCode != RC_HANDLE_CAMERA_PERM) {
  253. Log.d(TAG, "Got unexpected permission result: " + requestCode);
  254. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  255. return;
  256. }
  257.  
  258. if (grantResults.length != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  259. Log.d(TAG, "Camera permission granted - initialize the camera source");
  260. // we have permission, so create the camerasource
  261. boolean autoFocus = getIntent().getBooleanExtra(AutoFocus,false);
  262. boolean useFlash = getIntent().getBooleanExtra(UseFlash, false);
  263. createCameraSource(autoFocus, useFlash);
  264. return;
  265. }
  266.  
  267. Log.e(TAG, "Permission not granted: results len = " + grantResults.length +
  268. " Result code = " + (grantResults.length > 0 ? grantResults[0] : "(empty)"));
  269.  
  270. DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
  271. public void onClick(DialogInterface dialog, int id) {
  272. finish();
  273. }
  274. };
  275.  
  276. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  277. builder.setTitle("Multitracker sample")
  278. .setMessage(R.string.no_camera_permission)
  279. .setPositiveButton(R.string.ok, listener)
  280. .show();
  281. }
  282.  
  283. /**
  284. * Starts or restarts the camera source, if it exists. If the camera source doesn't exist yet
  285. * (e.g., because onResume was called before the camera source was created), this will be called
  286. * again when the camera source is created.
  287. */
  288. private void startCameraSource() throws SecurityException {
  289. // check that the device has play services available.
  290. int code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(
  291. getApplicationContext());
  292. if (code != ConnectionResult.SUCCESS) {
  293. Dialog dlg =
  294. GoogleApiAvailability.getInstance().getErrorDialog(this, code, RC_HANDLE_GMS);
  295. dlg.show();
  296. }
  297.  
  298. if (mCameraSource != null) {
  299. try {
  300. mPreview.start(mCameraSource, mGraphicOverlay);
  301. } catch (IOException e) {
  302. Log.e(TAG, "Unable to start camera source.", e);
  303. mCameraSource.release();
  304. mCameraSource = null;
  305. }
  306. }
  307. }
  308.  
  309. /**
  310. * onTap is called to capture the oldest barcode currently detected and
  311. * return it to the caller.
  312. *
  313. * @param rawX - the raw position of the tap
  314. * @param rawY - the raw position of the tap.
  315. * @return true if the activity is ending.
  316. */
  317. private boolean onTap(float rawX, float rawY) {
  318.  
  319. //TODO: use the tap position to select the barcode.
  320. BarcodeGraphic graphic = mGraphicOverlay.getFirstGraphic();
  321. Barcode barcode = null;
  322. if (graphic != null) {
  323. barcode = graphic.getBarcode();
  324. if (barcode != null) {
  325. Intent data = new Intent();
  326. data.putExtra(BarcodeObject, barcode);
  327. setResult(CommonStatusCodes.SUCCESS, data);
  328. finish();
  329. }
  330. else {
  331. Log.d(TAG, "barcode data is null");
  332. }
  333. }
  334. else {
  335. Log.d(TAG,"no barcode detected");
  336. }
  337. return barcode != null;
  338. }
  339.  
  340. private class CaptureGestureListener extends GestureDetector.SimpleOnGestureListener {
  341.  
  342. @Override
  343. public boolean onSingleTapConfirmed(MotionEvent e) {
  344. System.out.println(e.getRawX());
  345. System.out.println(e.getRawY());
  346. return onTap(e.getRawX(), e.getRawY()) || super.onSingleTapConfirmed(e);
  347. }
  348. }
  349.  
  350. private class ScaleListener implements ScaleGestureDetector.OnScaleGestureListener {
  351.  
  352. /**
  353. * Responds to scaling events for a gesture in progress.
  354. * Reported by pointer motion.
  355. *
  356. * @param detector The detector reporting the event - use this to
  357. * retrieve extended info about event state.
  358. * @return Whether or not the detector should consider this event
  359. * as handled. If an event was not handled, the detector
  360. * will continue to accumulate movement until an event is
  361. * handled. This can be useful if an application, for example,
  362. * only wants to update scaling factors if the change is
  363. * greater than 0.01.
  364. */
  365. @Override
  366. public boolean onScale(ScaleGestureDetector detector) {
  367. return false;
  368. }
  369.  
  370. /**
  371. * Responds to the beginning of a scaling gesture. Reported by
  372. * new pointers going down.
  373. *
  374. * @param detector The detector reporting the event - use this to
  375. * retrieve extended info about event state.
  376. * @return Whether or not the detector should continue recognizing
  377. * this gesture. For example, if a gesture is beginning
  378. * with a focal point outside of a region where it makes
  379. * sense, onScaleBegin() may return false to ignore the
  380. * rest of the gesture.
  381. */
  382. @Override
  383. public boolean onScaleBegin(ScaleGestureDetector detector) {
  384. return true;
  385. }
  386.  
  387. /**
  388. * Responds to the end of a scale gesture. Reported by existing
  389. * pointers going up.
  390. * <p/>
  391. * Once a scale has ended, {@link ScaleGestureDetector#getFocusX()}
  392. * and {@link ScaleGestureDetector#getFocusY()} will return focal point
  393. * of the pointers remaining on the screen.
  394. *
  395. * @param detector The detector reporting the event - use this to
  396. * retrieve extended info about event state.
  397. */
  398. @Override
  399. public void onScaleEnd(ScaleGestureDetector detector) {
  400. mCameraSource.doZoom(detector.getScaleFactor());
  401. }
  402. }
  403. }
Add Comment
Please, Sign In to add comment