Advertisement
Guest User

Untitled

a guest
Apr 11th, 2016
746
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 36.18 KB | None | 0 0
  1. public class Camera2BasicFragment extends Fragment
  2. implements FragmentCompat.OnRequestPermissionsResultCallback {
  3.  
  4. /**
  5. * Conversion from screen rotation to JPEG orientation.
  6. */
  7. private TextView fps;
  8. private long framePS;
  9. private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
  10. private static final int REQUEST_CAMERA_PERMISSION = 1;
  11. private static final String FRAGMENT_DIALOG = "dialog";
  12.  
  13. static {
  14. ORIENTATIONS.append(Surface.ROTATION_0, 90);
  15. ORIENTATIONS.append(Surface.ROTATION_90, 0);
  16. ORIENTATIONS.append(Surface.ROTATION_180, 270);
  17. ORIENTATIONS.append(Surface.ROTATION_270, 180);
  18. }
  19.  
  20. /**
  21. * Tag for the {@link Log}.
  22. */
  23. private static final String TAG = "Camera2BasicFragment";
  24.  
  25. /**
  26. * Camera state: Showing camera preview.
  27. */
  28. private static final int STATE_PREVIEW = 0;
  29.  
  30. /**
  31. * Camera state: Waiting for the focus to be locked.
  32. */
  33. private static final int STATE_WAITING_LOCK = 1;
  34.  
  35. /**
  36. * Camera state: Waiting for the exposure to be precapture state.
  37. */
  38. private static final int STATE_WAITING_PRECAPTURE = 2;
  39.  
  40. /**
  41. * Camera state: Waiting for the exposure state to be something other than precapture.
  42. */
  43. private static final int STATE_WAITING_NON_PRECAPTURE = 3;
  44.  
  45. /**
  46. * Camera state: Picture was taken.
  47. */
  48. private static final int STATE_PICTURE_TAKEN = 4;
  49.  
  50. /**
  51. * Max preview width that is guaranteed by Camera2 API
  52. */
  53. private static final int MAX_PREVIEW_WIDTH = 1920;
  54.  
  55. /**
  56. * Max preview height that is guaranteed by Camera2 API
  57. */
  58. private static final int MAX_PREVIEW_HEIGHT = 1080;
  59.  
  60. /**
  61. * {@link TextureView.SurfaceTextureListener} handles several lifecycle events on a
  62. * {@link TextureView}.
  63. */
  64. private final TextureView.SurfaceTextureListener mSurfaceTextureListener
  65. = new TextureView.SurfaceTextureListener() {
  66.  
  67. @Override
  68. public void onSurfaceTextureAvailable(SurfaceTexture texture, int width, int height) {
  69. openCamera(width, height);
  70. }
  71.  
  72. @Override
  73. public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int width, int height) {
  74. configureTransform(width, height);
  75. }
  76.  
  77. @Override
  78. public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) {
  79. return true;
  80. }
  81.  
  82. @Override
  83. public void onSurfaceTextureUpdated(SurfaceTexture texture) {
  84. }
  85.  
  86. };
  87.  
  88. /**
  89. * ID of the current {@link CameraDevice}.
  90. */
  91. private String mCameraId;
  92.  
  93. /**
  94. * An {@link AutoFitTextureView} for camera preview.
  95. */
  96. private AutoFitTextureView mTextureView;
  97.  
  98. /**
  99. * A {@link CameraCaptureSession } for camera preview.
  100. */
  101. private CameraCaptureSession mCaptureSession;
  102.  
  103. /**
  104. * A reference to the opened {@link CameraDevice}.
  105. */
  106. private CameraDevice mCameraDevice;
  107.  
  108. /**
  109. * The {@link android.util.Size} of camera preview.
  110. */
  111. private Size mPreviewSize;
  112.  
  113. /**
  114. * {@link CameraDevice.StateCallback} is called when {@link CameraDevice} changes its state.
  115. */
  116. private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
  117.  
  118. @Override
  119. public void onOpened(@NonNull CameraDevice cameraDevice) {
  120. // This method is called when the camera is opened. We start camera preview here.
  121. mCameraOpenCloseLock.release();
  122. mCameraDevice = cameraDevice;
  123. createCameraPreviewSession();
  124. }
  125.  
  126. @Override
  127. public void onDisconnected(@NonNull CameraDevice cameraDevice) {
  128. mCameraOpenCloseLock.release();
  129. cameraDevice.close();
  130. mCameraDevice = null;
  131. }
  132.  
  133. @Override
  134. public void onError(@NonNull CameraDevice cameraDevice, int error) {
  135. mCameraOpenCloseLock.release();
  136. cameraDevice.close();
  137. mCameraDevice = null;
  138. Activity activity = getActivity();
  139. if (null != activity) {
  140. activity.finish();
  141. }
  142. }
  143.  
  144. };
  145.  
  146. /**
  147. * An additional thread for running tasks that shouldn't block the UI.
  148. */
  149. private HandlerThread mBackgroundThread;
  150.  
  151. /**
  152. * A {@link Handler} for running tasks in the background.
  153. */
  154. private Handler mBackgroundHandler;
  155.  
  156. /**
  157. * An {@link ImageReader} that handles still image capture.
  158. */
  159. private ImageReader mImageReader;
  160.  
  161. /**
  162. * This is the output file for our picture.
  163. */
  164. private File mFile;
  165.  
  166. /**
  167. * This a callback object for the {@link ImageReader}. "onImageAvailable" will be called when a
  168. * still image is ready to be saved.
  169. */
  170. private final ImageReader.OnImageAvailableListener mOnImageAvailableListener
  171. = new ImageReader.OnImageAvailableListener() {
  172.  
  173. @Override
  174. public void onImageAvailable(ImageReader reader) {
  175. mBackgroundHandler.post(new ImageSaver(reader.acquireNextImage(), mFile));
  176. }
  177.  
  178. };
  179.  
  180. /**
  181. * {@link CaptureRequest.Builder} for the camera preview
  182. */
  183. private CaptureRequest.Builder mPreviewRequestBuilder;
  184.  
  185. /**
  186. * {@link CaptureRequest} generated by {@link #mPreviewRequestBuilder}
  187. */
  188. private CaptureRequest mPreviewRequest;
  189.  
  190. /**
  191. * The current state of camera state for taking pictures.
  192. *
  193. * @see #mCaptureCallback
  194. */
  195. private int mState = STATE_PREVIEW;
  196.  
  197. /**
  198. * A {@link Semaphore} to prevent the app from exiting before closing the camera.
  199. */
  200. private Semaphore mCameraOpenCloseLock = new Semaphore(1);
  201.  
  202. /**
  203. * Whether the current camera device supports Flash or not.
  204. */
  205. private boolean mFlashSupported;
  206.  
  207. /**
  208. * A {@link CameraCaptureSession.CaptureCallback} that handles events related to JPEG capture.
  209. */
  210. private CameraCaptureSession.CaptureCallback mCaptureCallback
  211. = new CameraCaptureSession.CaptureCallback() {
  212.  
  213. private void process(CaptureResult result) {
  214. switch (mState) {
  215. case STATE_PREVIEW: {
  216. framePS = result.getFrameNumber();
  217. // We have nothing to do when the camera preview is working normally.
  218. break;
  219. }
  220. case STATE_WAITING_LOCK: {
  221. Integer afState = result.get(CaptureResult.CONTROL_AF_STATE);
  222. if (afState == null) {
  223. captureStillPicture();
  224. } else if (CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED == afState ||
  225. CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED == afState) {
  226. // CONTROL_AE_STATE can be null on some devices
  227. Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
  228. if (aeState == null ||
  229. aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED) {
  230. mState = STATE_PICTURE_TAKEN;
  231. captureStillPicture();
  232. } else {
  233. runPrecaptureSequence();
  234. }
  235. }
  236. break;
  237. }
  238. case STATE_WAITING_PRECAPTURE: {
  239. // CONTROL_AE_STATE can be null on some devices
  240. Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
  241. if (aeState == null ||
  242. aeState == CaptureResult.CONTROL_AE_STATE_PRECAPTURE ||
  243. aeState == CaptureRequest.CONTROL_AE_STATE_FLASH_REQUIRED) {
  244. mState = STATE_WAITING_NON_PRECAPTURE;
  245. }
  246. break;
  247. }
  248. case STATE_WAITING_NON_PRECAPTURE: {
  249. // CONTROL_AE_STATE can be null on some devices
  250. Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
  251. if (aeState == null || aeState != CaptureResult.CONTROL_AE_STATE_PRECAPTURE) {
  252. mState = STATE_PICTURE_TAKEN;
  253. captureStillPicture();
  254. }
  255. break;
  256. }
  257. }
  258. }
  259.  
  260. @Override
  261. public void onCaptureProgressed(@NonNull CameraCaptureSession session,
  262. @NonNull CaptureRequest request,
  263. @NonNull CaptureResult partialResult) {
  264. process(partialResult);
  265. }
  266.  
  267. @Override
  268. public void onCaptureCompleted(@NonNull CameraCaptureSession session,
  269. @NonNull CaptureRequest request,
  270. @NonNull TotalCaptureResult result) {
  271. process(result);
  272. }
  273.  
  274. };
  275.  
  276. /**
  277. * Shows a {@link Toast} on the UI thread.
  278. *
  279. * @param text The message to show
  280. */
  281. private void showToast(final String text) {
  282. final Activity activity = getActivity();
  283. if (activity != null) {
  284. activity.runOnUiThread(new Runnable() {
  285. @Override
  286. public void run() {
  287. Toast.makeText(activity, text, Toast.LENGTH_SHORT).show();
  288. }
  289. });
  290. }
  291. }
  292.  
  293. /**
  294. * Given {@code choices} of {@code Size}s supported by a camera, choose the smallest one that
  295. * is at least as large as the respective texture view size, and that is at most as large as the
  296. * respective max size, and whose aspect ratio matches with the specified value. If such size
  297. * doesn't exist, choose the largest one that is at most as large as the respective max size,
  298. * and whose aspect ratio matches with the specified value.
  299. *
  300. * @param choices The list of sizes that the camera supports for the intended output
  301. * class
  302. * @param textureViewWidth The width of the texture view relative to sensor coordinate
  303. * @param textureViewHeight The height of the texture view relative to sensor coordinate
  304. * @param maxWidth The maximum width that can be chosen
  305. * @param maxHeight The maximum height that can be chosen
  306. * @param aspectRatio The aspect ratio
  307. * @return The optimal {@code Size}, or an arbitrary one if none were big enough
  308. */
  309. private static Size chooseOptimalSize(Size[] choices, int textureViewWidth,
  310. int textureViewHeight, int maxWidth, int maxHeight, Size aspectRatio) {
  311.  
  312. // Collect the supported resolutions that are at least as big as the preview Surface
  313. List<Size> bigEnough = new ArrayList<>();
  314. // Collect the supported resolutions that are smaller than the preview Surface
  315. List<Size> notBigEnough = new ArrayList<>();
  316. int w = aspectRatio.getWidth();
  317. int h = aspectRatio.getHeight();
  318. for (Size option : choices) {
  319. if (option.getWidth() <= maxWidth && option.getHeight() <= maxHeight &&
  320. option.getHeight() == option.getWidth() * h / w) {
  321. if (option.getWidth() >= textureViewWidth &&
  322. option.getHeight() >= textureViewHeight) {
  323. bigEnough.add(option);
  324. } else {
  325. notBigEnough.add(option);
  326. }
  327. }
  328. }
  329.  
  330. // Pick the smallest of those big enough. If there is no one big enough, pick the
  331. // largest of those not big enough.
  332. if (bigEnough.size() > 0) {
  333. return Collections.min(bigEnough, new CompareSizesByArea());
  334. } else if (notBigEnough.size() > 0) {
  335. return Collections.max(notBigEnough, new CompareSizesByArea());
  336. } else {
  337. Log.e(TAG, "Couldn't find any suitable preview size");
  338. return choices[0];
  339. }
  340. }
  341.  
  342. public static Camera2BasicFragment newInstance() {
  343. return new Camera2BasicFragment();
  344. }
  345.  
  346. @Override
  347. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  348. Bundle savedInstanceState) {
  349. return inflater.inflate(R.layout.fragment_camera2_basic, container, false);
  350. }
  351.  
  352. @Override
  353. public void onViewCreated(final View view, Bundle savedInstanceState) {
  354. mTextureView = (AutoFitTextureView) view.findViewById(R.id.texture);
  355. }
  356.  
  357. @Override
  358. public void onActivityCreated(Bundle savedInstanceState) {
  359. super.onActivityCreated(savedInstanceState);
  360. mFile = new File(getActivity().getExternalFilesDir(null), "pic.jpg");
  361. }
  362.  
  363. @Override
  364. public void onResume() {
  365. super.onResume();
  366. startBackgroundThread();
  367.  
  368. // When the screen is turned off and turned back on, the SurfaceTexture is already
  369. // available, and "onSurfaceTextureAvailable" will not be called. In that case, we can open
  370. // a camera and start preview from here (otherwise, we wait until the surface is ready in
  371. // the SurfaceTextureListener).
  372. if (mTextureView.isAvailable()) {
  373. openCamera(mTextureView.getWidth(), mTextureView.getHeight());
  374. } else {
  375. mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
  376. }
  377. }
  378.  
  379. @Override
  380. public void onPause() {
  381. closeCamera();
  382. stopBackgroundThread();
  383. super.onPause();
  384. }
  385.  
  386. private void requestCameraPermission() {
  387. if (FragmentCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
  388. new ConfirmationDialog().show(getChildFragmentManager(), FRAGMENT_DIALOG);
  389. } else {
  390. FragmentCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
  391. REQUEST_CAMERA_PERMISSION);
  392. }
  393. }
  394.  
  395. @Override
  396. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
  397. @NonNull int[] grantResults) {
  398. if (requestCode == REQUEST_CAMERA_PERMISSION) {
  399. if (grantResults.length != 1 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
  400. ErrorDialog.newInstance("This sample needs camera permission.")
  401. .show(getChildFragmentManager(), FRAGMENT_DIALOG);
  402. }
  403. } else {
  404. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  405. }
  406. }
  407.  
  408. /**
  409. * Sets up member variables related to camera.
  410. *
  411. * @param width The width of available size for camera preview
  412. * @param height The height of available size for camera preview
  413. */
  414. private void setUpCameraOutputs(int width, int height) {
  415. Activity activity = getActivity();
  416. CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
  417. try {
  418. for (String cameraId : manager.getCameraIdList()) {
  419. CameraCharacteristics characteristics
  420. = manager.getCameraCharacteristics(cameraId);
  421.  
  422. // We don't use a front facing camera in this sample.
  423. Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
  424. if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
  425. continue;
  426. }
  427.  
  428. StreamConfigurationMap map = characteristics.get(
  429. CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
  430. if (map == null) {
  431. continue;
  432. }
  433.  
  434. // For still image captures, we use the largest available size.
  435. Size largest = Collections.max(
  436. Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
  437. new CompareSizesByArea());
  438. mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(),
  439. ImageFormat.JPEG, /*maxImages*/2);
  440. mImageReader.setOnImageAvailableListener(
  441. mOnImageAvailableListener, mBackgroundHandler);
  442.  
  443. // Find out if we need to swap dimension to get the preview size relative to sensor
  444. // coordinate.
  445. int displayRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
  446. int sensorOrientation =
  447. characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
  448. boolean swappedDimensions = false;
  449. switch (displayRotation) {
  450. case Surface.ROTATION_0:
  451. case Surface.ROTATION_180:
  452. if (sensorOrientation == 90 || sensorOrientation == 270) {
  453. swappedDimensions = true;
  454. }
  455. break;
  456. case Surface.ROTATION_90:
  457. case Surface.ROTATION_270:
  458. if (sensorOrientation == 0 || sensorOrientation == 180) {
  459. swappedDimensions = true;
  460. }
  461. break;
  462. default:
  463. Log.e(TAG, "Display rotation is invalid: " + displayRotation);
  464. }
  465.  
  466. Point displaySize = new Point();
  467. activity.getWindowManager().getDefaultDisplay().getSize(displaySize);
  468. int rotatedPreviewWidth = width;
  469. int rotatedPreviewHeight = height;
  470. int maxPreviewWidth = displaySize.x;
  471. int maxPreviewHeight = displaySize.y;
  472.  
  473. if (swappedDimensions) {
  474. rotatedPreviewWidth = height;
  475. rotatedPreviewHeight = width;
  476. maxPreviewWidth = displaySize.y;
  477. maxPreviewHeight = displaySize.x;
  478. }
  479.  
  480. if (maxPreviewWidth > MAX_PREVIEW_WIDTH) {
  481. maxPreviewWidth = MAX_PREVIEW_WIDTH;
  482. }
  483.  
  484. if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) {
  485. maxPreviewHeight = MAX_PREVIEW_HEIGHT;
  486. }
  487.  
  488. // Danger, W.R.! Attempting to use too large a preview size could exceed the camera
  489. // bus' bandwidth limitation, resulting in gorgeous previews but the storage of
  490. // garbage capture data.
  491. mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
  492. rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
  493. maxPreviewHeight, largest);
  494.  
  495. // We fit the aspect ratio of TextureView to the size of preview we picked.
  496. int orientation = getResources().getConfiguration().orientation;
  497. if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
  498. mTextureView.setAspectRatio(
  499. mPreviewSize.getWidth(), mPreviewSize.getHeight());
  500. } else {
  501. mTextureView.setAspectRatio(
  502. mPreviewSize.getHeight(), mPreviewSize.getWidth());
  503. }
  504.  
  505. // Check if the flash is supported.
  506. Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
  507. mFlashSupported = available == null ? false : available;
  508.  
  509. mCameraId = cameraId;
  510. return;
  511. }
  512. } catch (CameraAccessException e) {
  513. e.printStackTrace();
  514. } catch (NullPointerException e) {
  515. // Currently an NPE is thrown when the Camera2API is used but not supported on the
  516. // device this code runs.
  517. ErrorDialog.newInstance("Errore Camera")
  518. .show(getChildFragmentManager(), FRAGMENT_DIALOG);
  519. }
  520. }
  521.  
  522. /**
  523. * Opens the camera specified by {@link Camera2BasicFragment#mCameraId}.
  524. */
  525. private void openCamera(int width, int height) {
  526. if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
  527. != PackageManager.PERMISSION_GRANTED) {
  528. requestCameraPermission();
  529. return;
  530. }
  531. setUpCameraOutputs(width, height);
  532. configureTransform(width, height);
  533. Activity activity = getActivity();
  534. CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
  535. try {
  536. if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
  537. throw new RuntimeException("Time out waiting to lock camera opening.");
  538. }
  539. manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
  540. } catch (CameraAccessException e) {
  541. e.printStackTrace();
  542. } catch (InterruptedException e) {
  543. throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
  544. }
  545. }
  546.  
  547. /**
  548. * Closes the current {@link CameraDevice}.
  549. */
  550. private void closeCamera() {
  551. try {
  552. mCameraOpenCloseLock.acquire();
  553. if (null != mCaptureSession) {
  554. mCaptureSession.close();
  555. mCaptureSession = null;
  556. }
  557. if (null != mCameraDevice) {
  558. mCameraDevice.close();
  559. mCameraDevice = null;
  560. }
  561. if (null != mImageReader) {
  562. mImageReader.close();
  563. mImageReader = null;
  564. }
  565. } catch (InterruptedException e) {
  566. throw new RuntimeException("Interrupted while trying to lock camera closing.", e);
  567. } finally {
  568. mCameraOpenCloseLock.release();
  569. }
  570. }
  571.  
  572. /**
  573. * Starts a background thread and its {@link Handler}.
  574. */
  575. private void startBackgroundThread() {
  576. mBackgroundThread = new HandlerThread("CameraBackground");
  577. mBackgroundThread.start();
  578. mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
  579. }
  580.  
  581. /**
  582. * Stops the background thread and its {@link Handler}.
  583. */
  584. private void stopBackgroundThread() {
  585. mBackgroundThread.quitSafely();
  586. try {
  587. mBackgroundThread.join();
  588. mBackgroundThread = null;
  589. mBackgroundHandler = null;
  590. } catch (InterruptedException e) {
  591. e.printStackTrace();
  592. }
  593. }
  594.  
  595. /**
  596. * Creates a new {@link CameraCaptureSession} for camera preview.
  597. */
  598. private void createCameraPreviewSession() {
  599. try {
  600. SurfaceTexture texture = mTextureView.getSurfaceTexture();
  601. assert texture != null;
  602.  
  603. // We configure the size of default buffer to be the size of camera preview we want.
  604. texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
  605.  
  606. // This is the output Surface we need to start preview.
  607. Surface surface = new Surface(texture);
  608. // We set up a CaptureRequest.Builder with the output Surface.
  609. mPreviewRequestBuilder
  610. = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
  611. mPreviewRequestBuilder.addTarget(surface);
  612.  
  613. // Here, we create a CameraCaptureSession for camera preview.
  614. mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
  615. new CameraCaptureSession.StateCallback() {
  616.  
  617. @Override
  618. public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
  619. // The camera is already closed
  620. if (null == mCameraDevice) {
  621. return;
  622. }
  623.  
  624. // When the session is ready, we start displaying the preview.
  625. mCaptureSession = cameraCaptureSession;
  626. try {
  627. // Auto focus should be continuous for camera preview.
  628. mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
  629. CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
  630. // Flash is automatically enabled when necessary.
  631. setAutoFlash(mPreviewRequestBuilder);
  632. // Finally, we start displaying the camera preview.
  633. mPreviewRequest = mPreviewRequestBuilder.build();
  634. mCaptureSession.setRepeatingRequest(mPreviewRequest,
  635. mCaptureCallback, mBackgroundHandler);
  636. } catch (CameraAccessException e) {
  637. e.printStackTrace();
  638. }
  639. }
  640.  
  641. @Override
  642. public void onConfigureFailed(
  643. @NonNull CameraCaptureSession cameraCaptureSession) {
  644. showToast("Failed");
  645. }
  646. }, null
  647. );
  648. } catch (CameraAccessException e) {
  649. e.printStackTrace();
  650. }
  651. }
  652.  
  653. /**
  654. * Configures the necessary {@link android.graphics.Matrix} transformation to `mTextureView`.
  655. * This method should be called after the camera preview size is determined in
  656. * setUpCameraOutputs and also the size of `mTextureView` is fixed.
  657. *
  658. * @param viewWidth The width of `mTextureView`
  659. * @param viewHeight The height of `mTextureView`
  660. */
  661. private void configureTransform(int viewWidth, int viewHeight) {
  662. Activity activity = getActivity();
  663. if (null == mTextureView || null == mPreviewSize || null == activity) {
  664. return;
  665. }
  666. int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
  667. Matrix matrix = new Matrix();
  668. RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
  669. RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
  670. float centerX = viewRect.centerX();
  671. float centerY = viewRect.centerY();
  672. if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
  673. bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
  674. matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
  675. float scale = Math.max(
  676. (float) viewHeight / mPreviewSize.getHeight(),
  677. (float) viewWidth / mPreviewSize.getWidth());
  678. matrix.postScale(scale, scale, centerX, centerY);
  679. matrix.postRotate(90 * (rotation - 2), centerX, centerY);
  680. } else if (Surface.ROTATION_180 == rotation) {
  681. matrix.postRotate(180, centerX, centerY);
  682. }
  683. mTextureView.setTransform(matrix);
  684. }
  685.  
  686. /**
  687. * Initiate a still image capture.
  688. */
  689. private void takePicture() {
  690. lockFocus();
  691. }
  692.  
  693. /**
  694. * Lock the focus as the first step for a still image capture.
  695. */
  696. private void lockFocus() {
  697. try {
  698. // This is how to tell the camera to lock focus.
  699. mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
  700. CameraMetadata.CONTROL_AF_TRIGGER_START);
  701. // Tell #mCaptureCallback to wait for the lock.
  702. mState = STATE_WAITING_LOCK;
  703. mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
  704. mBackgroundHandler);
  705. } catch (CameraAccessException e) {
  706. e.printStackTrace();
  707. }
  708. }
  709.  
  710. /**
  711. * Run the precapture sequence for capturing a still image. This method should be called when
  712. * we get a response in {@link #mCaptureCallback} from {@link #lockFocus()}.
  713. */
  714. private void runPrecaptureSequence() {
  715. try {
  716. // This is how to tell the camera to trigger.
  717. mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
  718. CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START);
  719. // Tell #mCaptureCallback to wait for the precapture sequence to be set.
  720. mState = STATE_WAITING_PRECAPTURE;
  721. mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
  722. mBackgroundHandler);
  723. } catch (CameraAccessException e) {
  724. e.printStackTrace();
  725. }
  726. }
  727.  
  728. /**
  729. * Capture a still picture. This method should be called when we get a response in
  730. * {@link #mCaptureCallback} from both {@link #lockFocus()}.
  731. */
  732. private void captureStillPicture() {
  733. try {
  734. final Activity activity = getActivity();
  735. if (null == activity || null == mCameraDevice) {
  736. return;
  737. }
  738. // This is the CaptureRequest.Builder that we use to take a picture.
  739. final CaptureRequest.Builder captureBuilder =
  740. mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
  741. captureBuilder.addTarget(mImageReader.getSurface());
  742.  
  743. // Use the same AE and AF modes as the preview.
  744. captureBuilder.set(CaptureRequest.CONTROL_AF_MODE,
  745. CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
  746. setAutoFlash(captureBuilder);
  747.  
  748. // Orientation
  749. int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
  750. captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
  751.  
  752. CameraCaptureSession.CaptureCallback CaptureCallback
  753. = new CameraCaptureSession.CaptureCallback() {
  754.  
  755. @Override
  756. public void onCaptureCompleted(@NonNull CameraCaptureSession session,
  757. @NonNull CaptureRequest request,
  758. @NonNull TotalCaptureResult result) {
  759. showToast("Saved: " + mFile);
  760. Log.d(TAG, mFile.toString());
  761. unlockFocus();
  762. }
  763. };
  764.  
  765. mCaptureSession.stopRepeating();
  766. mCaptureSession.capture(captureBuilder.build(), CaptureCallback, null);
  767. } catch (CameraAccessException e) {
  768. e.printStackTrace();
  769. }
  770. }
  771.  
  772. /**
  773. * Unlock the focus. This method should be called when still image capture sequence is
  774. * finished.
  775. */
  776. private void unlockFocus() {
  777. try {
  778. // Reset the auto-focus trigger
  779. mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
  780. CameraMetadata.CONTROL_AF_TRIGGER_CANCEL);
  781. setAutoFlash(mPreviewRequestBuilder);
  782. mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
  783. mBackgroundHandler);
  784. // After this, the camera will go back to the normal state of preview.
  785. mState = STATE_PREVIEW;
  786. mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback,
  787. mBackgroundHandler);
  788. } catch (CameraAccessException e) {
  789. e.printStackTrace();
  790. }
  791. }
  792.  
  793. private void setAutoFlash(CaptureRequest.Builder requestBuilder) {
  794. if (mFlashSupported) {
  795. requestBuilder.set(CaptureRequest.CONTROL_AE_MODE,
  796. CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
  797. }
  798. }
  799.  
  800. /**
  801. * Saves a JPEG {@link Image} into the specified {@link File}.
  802. */
  803. private static class ImageSaver implements Runnable {
  804.  
  805. /**
  806. * The JPEG image
  807. */
  808. private final Image mImage;
  809. /**
  810. * The file we save the image into.
  811. */
  812. private final File mFile;
  813.  
  814. public ImageSaver(Image image, File file) {
  815. mImage = image;
  816. mFile = file;
  817. }
  818.  
  819. @Override
  820. public void run() {
  821. ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
  822. byte[] bytes = new byte[buffer.remaining()];
  823. buffer.get(bytes);
  824. FileOutputStream output = null;
  825. try {
  826. output = new FileOutputStream(mFile);
  827. output.write(bytes);
  828. } catch (IOException e) {
  829. e.printStackTrace();
  830. } finally {
  831. mImage.close();
  832. if (null != output) {
  833. try {
  834. output.close();
  835. } catch (IOException e) {
  836. e.printStackTrace();
  837. }
  838. }
  839. }
  840. }
  841.  
  842. }
  843.  
  844. /**
  845. * Compares two {@code Size}s based on their areas.
  846. */
  847. static class CompareSizesByArea implements Comparator<Size> {
  848.  
  849. @Override
  850. public int compare(Size lhs, Size rhs) {
  851. // We cast here to ensure the multiplications won't overflow
  852. return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
  853. (long) rhs.getWidth() * rhs.getHeight());
  854. }
  855.  
  856. }
  857.  
  858. /**
  859. * Shows an error message dialog.
  860. */
  861. public static class ErrorDialog extends DialogFragment {
  862.  
  863. private static final String ARG_MESSAGE = "message";
  864.  
  865. public static ErrorDialog newInstance(String message) {
  866. ErrorDialog dialog = new ErrorDialog();
  867. Bundle args = new Bundle();
  868. args.putString(ARG_MESSAGE, message);
  869. dialog.setArguments(args);
  870. return dialog;
  871. }
  872.  
  873. @Override
  874. public Dialog onCreateDialog(Bundle savedInstanceState) {
  875. final Activity activity = getActivity();
  876. return new AlertDialog.Builder(activity)
  877. .setMessage(getArguments().getString(ARG_MESSAGE))
  878. .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
  879. @Override
  880. public void onClick(DialogInterface dialogInterface, int i) {
  881. activity.finish();
  882. }
  883. })
  884. .create();
  885. }
  886.  
  887. }
  888.  
  889. /**
  890. * Shows OK/Cancel confirmation dialog about camera permission.
  891. */
  892. public static class ConfirmationDialog extends DialogFragment {
  893.  
  894. @Override
  895. public Dialog onCreateDialog(Bundle savedInstanceState) {
  896. final Fragment parent = getParentFragment();
  897. return new AlertDialog.Builder(getActivity())
  898. .setMessage("This sample needs camera permission")
  899. .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
  900. @Override
  901. public void onClick(DialogInterface dialog, int which) {
  902. FragmentCompat.requestPermissions(parent,
  903. new String[]{Manifest.permission.CAMERA},
  904. REQUEST_CAMERA_PERMISSION);
  905. }
  906. })
  907. .setNegativeButton(android.R.string.cancel,
  908. new DialogInterface.OnClickListener() {
  909. @Override
  910. public void onClick(DialogInterface dialog, int which) {
  911. Activity activity = parent.getActivity();
  912. if (activity != null) {
  913. activity.finish();
  914. }
  915. }
  916. })
  917. .create();
  918. }
  919. }
  920.  
  921. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement