Guest User

Untitled

a guest
Apr 11th, 2016
829
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 40.61 KB | None | 0 0
  1. public class Camera2BasicFragmentFront 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 Camera2BasicFragmentFront newInstance() {
  343. return new Camera2BasicFragmentFront();
  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. * Get front camera id
  410. * @param cManager
  411. * @return
  412. */
  413. String getFrontFacingCameraId(CameraManager cManager){
  414. try {
  415. for(final String cameraId : cManager.getCameraIdList()){
  416. CameraCharacteristics characteristics = cManager.getCameraCharacteristics(cameraId);
  417. int cOrientation = characteristics.get(CameraCharacteristics.LENS_FACING);
  418. if(cOrientation == CameraCharacteristics.LENS_FACING_FRONT) return cameraId;
  419. }
  420. } catch (CameraAccessException e) {
  421. e.printStackTrace();
  422. }
  423. return null;
  424. }
  425.  
  426. /**
  427. * Sets up member variables related to camera.
  428. *
  429. * @param width The width of available size for camera preview
  430. * @param height The height of available size for camera preview
  431. */
  432. private void setUpCameraOutputs(int width, int height) {
  433. Activity activity = getActivity();
  434. CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
  435. try {
  436. for (String cameraId : manager.getCameraIdList()) {
  437. CameraCharacteristics characteristics
  438. = manager.getCameraCharacteristics(cameraId);
  439.  
  440. // We don't use a front facing camera in this sample.
  441. Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
  442. if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
  443. continue;
  444. }
  445. //Get front camera ID
  446. mCameraId = getFrontFacingCameraId(manager);
  447.  
  448. StreamConfigurationMap map = characteristics.get(
  449. CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
  450. if (map == null) {
  451. continue;
  452. }
  453.  
  454. // For still image captures, we use the largest available size.
  455. Size largest = Collections.max(
  456. Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
  457. new CompareSizesByArea());
  458. mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(),
  459. ImageFormat.JPEG, /*maxImages*/2);
  460. mImageReader.setOnImageAvailableListener(
  461. mOnImageAvailableListener, mBackgroundHandler);
  462.  
  463. // Find out if we need to swap dimension to get the preview size relative to sensor
  464. // coordinate.
  465. int displayRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
  466. int sensorOrientation =
  467. characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
  468. boolean swappedDimensions = false;
  469. switch (displayRotation) {
  470. case Surface.ROTATION_0:
  471. case Surface.ROTATION_180:
  472. if (sensorOrientation == 90 || sensorOrientation == 270) {
  473. swappedDimensions = true;
  474. }
  475. break;
  476. case Surface.ROTATION_90:
  477. case Surface.ROTATION_270:
  478. if (sensorOrientation == 0 || sensorOrientation == 180) {
  479. swappedDimensions = true;
  480. }
  481. break;
  482. default:
  483. Log.e(TAG, "Display rotation is invalid: " + displayRotation);
  484. }
  485.  
  486. Point displaySize = new Point();
  487. activity.getWindowManager().getDefaultDisplay().getSize(displaySize);
  488. int rotatedPreviewWidth = width;
  489. int rotatedPreviewHeight = height;
  490. int maxPreviewWidth = displaySize.x;
  491. int maxPreviewHeight = displaySize.y;
  492.  
  493. if (swappedDimensions) {
  494. rotatedPreviewWidth = height;
  495. rotatedPreviewHeight = width;
  496. maxPreviewWidth = displaySize.y;
  497. maxPreviewHeight = displaySize.x;
  498. }
  499.  
  500. if (maxPreviewWidth > MAX_PREVIEW_WIDTH) {
  501. maxPreviewWidth = MAX_PREVIEW_WIDTH;
  502. }
  503.  
  504. if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) {
  505. maxPreviewHeight = MAX_PREVIEW_HEIGHT;
  506. }
  507.  
  508. // Danger, W.R.! Attempting to use too large a preview size could exceed the camera
  509. // bus' bandwidth limitation, resulting in gorgeous previews but the storage of
  510. // garbage capture data.
  511. mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
  512. rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
  513. maxPreviewHeight, largest);
  514.  
  515. // We fit the aspect ratio of TextureView to the size of preview we picked.
  516. int orientation = getResources().getConfiguration().orientation;
  517. if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
  518. mTextureView.setAspectRatio(
  519. mPreviewSize.getWidth(), mPreviewSize.getHeight());
  520. } else {
  521. mTextureView.setAspectRatio(
  522. mPreviewSize.getHeight(), mPreviewSize.getWidth());
  523. }
  524.  
  525. // Check if the flash is supported.
  526. Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
  527. mFlashSupported = available == null ? false : available;
  528.  
  529. //mCameraId = cameraId;
  530. return;
  531. }
  532. } catch (CameraAccessException e) {
  533. e.printStackTrace();
  534. } catch (NullPointerException e) {
  535. // Currently an NPE is thrown when the Camera2API is used but not supported on the
  536. // device this code runs.
  537. ErrorDialog.newInstance("Errore Camera")
  538. .show(getChildFragmentManager(), FRAGMENT_DIALOG);
  539. }
  540. }
  541.  
  542. /**
  543. * Opens the camera specified by {@link Camera2BasicFragment#mCameraId}.
  544. */
  545. private void openCamera(int width, int height) {
  546. if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
  547. != PackageManager.PERMISSION_GRANTED) {
  548. requestCameraPermission();
  549. return;
  550. }
  551. setUpCameraOutputs(width, height);
  552. configureTransform(width, height);
  553. Activity activity = getActivity();
  554. CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
  555. try {
  556. if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
  557. throw new RuntimeException("Time out waiting to lock camera opening.");
  558. }
  559. manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
  560. } catch (CameraAccessException e) {
  561. e.printStackTrace();
  562. } catch (InterruptedException e) {
  563. throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
  564. }
  565. }
  566.  
  567. /**
  568. * Closes the current {@link CameraDevice}.
  569. */
  570. private void closeCamera() {
  571. try {
  572. mCameraOpenCloseLock.acquire();
  573. if (null != mCaptureSession) {
  574. mCaptureSession.close();
  575. mCaptureSession = null;
  576. }
  577. if (null != mCameraDevice) {
  578. mCameraDevice.close();
  579. mCameraDevice = null;
  580. }
  581. if (null != mImageReader) {
  582. mImageReader.close();
  583. mImageReader = null;
  584. }
  585. } catch (InterruptedException e) {
  586. throw new RuntimeException("Interrupted while trying to lock camera closing.", e);
  587. } finally {
  588. mCameraOpenCloseLock.release();
  589. }
  590. }
  591.  
  592. /**
  593. * Starts a background thread and its {@link Handler}.
  594. */
  595. private void startBackgroundThread() {
  596. mBackgroundThread = new HandlerThread("CameraBackground");
  597. mBackgroundThread.start();
  598. mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
  599. }
  600.  
  601. /**
  602. * Stops the background thread and its {@link Handler}.
  603. */
  604. private void stopBackgroundThread() {
  605. mBackgroundThread.quitSafely();
  606. try {
  607. mBackgroundThread.join();
  608. mBackgroundThread = null;
  609. mBackgroundHandler = null;
  610. } catch (InterruptedException e) {
  611. e.printStackTrace();
  612. }
  613. }
  614.  
  615. /**
  616. * Creates a new {@link CameraCaptureSession} for camera preview.
  617. */
  618. private void createCameraPreviewSession() {
  619. try {
  620. SurfaceTexture texture = mTextureView.getSurfaceTexture();
  621. assert texture != null;
  622.  
  623. // We configure the size of default buffer to be the size of camera preview we want.
  624. texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
  625.  
  626. // This is the output Surface we need to start preview.
  627. Surface surface = new Surface(texture);
  628. // We set up a CaptureRequest.Builder with the output Surface.
  629. mPreviewRequestBuilder
  630. = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
  631. mPreviewRequestBuilder.addTarget(surface);
  632.  
  633. // Here, we create a CameraCaptureSession for camera preview.
  634. mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
  635. new CameraCaptureSession.StateCallback() {
  636.  
  637. @Override
  638. public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
  639. // The camera is already closed
  640. if (null == mCameraDevice) {
  641. return;
  642. }
  643.  
  644. // When the session is ready, we start displaying the preview.
  645. mCaptureSession = cameraCaptureSession;
  646. try {
  647. // Auto focus should be continuous for camera preview.
  648. mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
  649. CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
  650. // Flash is automatically enabled when necessary.
  651. setAutoFlash(mPreviewRequestBuilder);
  652. // Finally, we start displaying the camera preview.
  653. mPreviewRequest = mPreviewRequestBuilder.build();
  654. mCaptureSession.setRepeatingRequest(mPreviewRequest,
  655. mCaptureCallback, mBackgroundHandler);
  656. } catch (CameraAccessException e) {
  657. e.printStackTrace();
  658. }
  659. }
  660.  
  661. @Override
  662. public void onConfigureFailed(
  663. @NonNull CameraCaptureSession cameraCaptureSession) {
  664. showToast("Failed");
  665. }
  666. }, null
  667. );
  668. } catch (CameraAccessException e) {
  669. e.printStackTrace();
  670. }
  671. }
  672.  
  673. /**
  674. * Configures the necessary {@link android.graphics.Matrix} transformation to `mTextureView`.
  675. * This method should be called after the camera preview size is determined in
  676. * setUpCameraOutputs and also the size of `mTextureView` is fixed.
  677. *
  678. * @param viewWidth The width of `mTextureView`
  679. * @param viewHeight The height of `mTextureView`
  680. */
  681. private void configureTransform(int viewWidth, int viewHeight) {
  682. Activity activity = getActivity();
  683. if (null == mTextureView || null == mPreviewSize || null == activity) {
  684. return;
  685. }
  686. int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
  687. Matrix matrix = new Matrix();
  688. RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
  689. RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
  690. float centerX = viewRect.centerX();
  691. float centerY = viewRect.centerY();
  692. if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
  693. bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
  694. matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
  695. float scale = Math.max(
  696. (float) viewHeight / mPreviewSize.getHeight(),
  697. (float) viewWidth / mPreviewSize.getWidth());
  698. matrix.postScale(scale, scale, centerX, centerY);
  699. matrix.postRotate(90 * (rotation - 2), centerX, centerY);
  700. } else if (Surface.ROTATION_180 == rotation) {
  701. matrix.postRotate(180, centerX, centerY);
  702. }
  703. mTextureView.setTransform(matrix);
  704. }
  705.  
  706. /**
  707. * Initiate a still image capture.
  708. */
  709. private void takePicture() {
  710. lockFocus();
  711. }
  712.  
  713. /**
  714. * Lock the focus as the first step for a still image capture.
  715. */
  716. private void lockFocus() {
  717. try {
  718. // This is how to tell the camera to lock focus.
  719. mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
  720. CameraMetadata.CONTROL_AF_TRIGGER_START);
  721. // Tell #mCaptureCallback to wait for the lock.
  722. mState = STATE_WAITING_LOCK;
  723. mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
  724. mBackgroundHandler);
  725. } catch (CameraAccessException e) {
  726. e.printStackTrace();
  727. }
  728. }
  729.  
  730. /**
  731. * Run the precapture sequence for capturing a still image. This method should be called when
  732. * we get a response in {@link #mCaptureCallback} from {@link #lockFocus()}.
  733. */
  734. private void runPrecaptureSequence() {
  735. try {
  736. // This is how to tell the camera to trigger.
  737. mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
  738. CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START);
  739. // Tell #mCaptureCallback to wait for the precapture sequence to be set.
  740. mState = STATE_WAITING_PRECAPTURE;
  741. mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
  742. mBackgroundHandler);
  743. } catch (CameraAccessException e) {
  744. e.printStackTrace();
  745. }
  746. }
  747.  
  748. /**
  749. * Capture a still picture. This method should be called when we get a response in
  750. * {@link #mCaptureCallback} from both {@link #lockFocus()}.
  751. */
  752. private void captureStillPicture() {
  753. try {
  754. final Activity activity = getActivity();
  755. if (null == activity || null == mCameraDevice) {
  756. return;
  757. }
  758. // This is the CaptureRequest.Builder that we use to take a picture.
  759. final CaptureRequest.Builder captureBuilder =
  760. mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
  761. captureBuilder.addTarget(mImageReader.getSurface());
  762.  
  763. // Use the same AE and AF modes as the preview.
  764. captureBuilder.set(CaptureRequest.CONTROL_AF_MODE,
  765. CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
  766. setAutoFlash(captureBuilder);
  767.  
  768. // Orientation
  769. int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
  770. captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
  771.  
  772. CameraCaptureSession.CaptureCallback CaptureCallback
  773. = new CameraCaptureSession.CaptureCallback() {
  774.  
  775. @Override
  776. public void onCaptureCompleted(@NonNull CameraCaptureSession session,
  777. @NonNull CaptureRequest request,
  778. @NonNull TotalCaptureResult result) {
  779. showToast("Saved: " + mFile);
  780. Log.d(TAG, mFile.toString());
  781. unlockFocus();
  782. }
  783. };
  784.  
  785. mCaptureSession.stopRepeating();
  786. mCaptureSession.capture(captureBuilder.build(), CaptureCallback, null);
  787. } catch (CameraAccessException e) {
  788. e.printStackTrace();
  789. }
  790. }
  791.  
  792. /**
  793. * Unlock the focus. This method should be called when still image capture sequence is
  794. * finished.
  795. */
  796. private void unlockFocus() {
  797. try {
  798. // Reset the auto-focus trigger
  799. mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
  800. CameraMetadata.CONTROL_AF_TRIGGER_CANCEL);
  801. setAutoFlash(mPreviewRequestBuilder);
  802. mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
  803. mBackgroundHandler);
  804. // After this, the camera will go back to the normal state of preview.
  805. mState = STATE_PREVIEW;
  806. mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback,
  807. mBackgroundHandler);
  808. } catch (CameraAccessException e) {
  809. e.printStackTrace();
  810. }
  811. }
  812.  
  813. private void setAutoFlash(CaptureRequest.Builder requestBuilder) {
  814. if (mFlashSupported) {
  815. requestBuilder.set(CaptureRequest.CONTROL_AE_MODE,
  816. CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
  817. }
  818. }
  819.  
  820. /**
  821. * Saves a JPEG {@link Image} into the specified {@link File}.
  822. */
  823. private static class ImageSaver implements Runnable {
  824.  
  825. /**
  826. * The JPEG image
  827. */
  828. private final Image mImage;
  829. /**
  830. * The file we save the image into.
  831. */
  832. private final File mFile;
  833.  
  834. public ImageSaver(Image image, File file) {
  835. mImage = image;
  836. mFile = file;
  837. }
  838.  
  839. @Override
  840. public void run() {
  841. ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
  842. byte[] bytes = new byte[buffer.remaining()];
  843. buffer.get(bytes);
  844. FileOutputStream output = null;
  845. try {
  846. output = new FileOutputStream(mFile);
  847. output.write(bytes);
  848. } catch (IOException e) {
  849. e.printStackTrace();
  850. } finally {
  851. mImage.close();
  852. if (null != output) {
  853. try {
  854. output.close();
  855. } catch (IOException e) {
  856. e.printStackTrace();
  857. }
  858. }
  859. }
  860. }
  861.  
  862. }
  863.  
  864. /**
  865. * Compares two {@code Size}s based on their areas.
  866. */
  867. static class CompareSizesByArea implements Comparator<Size> {
  868.  
  869. @Override
  870. public int compare(Size lhs, Size rhs) {
  871. // We cast here to ensure the multiplications won't overflow
  872. return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
  873. (long) rhs.getWidth() * rhs.getHeight());
  874. }
  875.  
  876. }
  877.  
  878. /**
  879. * Shows an error message dialog.
  880. */
  881. public static class ErrorDialog extends DialogFragment {
  882.  
  883. private static final String ARG_MESSAGE = "message";
  884.  
  885. public static ErrorDialog newInstance(String message) {
  886. ErrorDialog dialog = new ErrorDialog();
  887. Bundle args = new Bundle();
  888. args.putString(ARG_MESSAGE, message);
  889. dialog.setArguments(args);
  890. return dialog;
  891. }
  892.  
  893. @Override
  894. public Dialog onCreateDialog(Bundle savedInstanceState) {
  895. final Activity activity = getActivity();
  896. return new AlertDialog.Builder(activity)
  897. .setMessage(getArguments().getString(ARG_MESSAGE))
  898. .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
  899. @Override
  900. public void onClick(DialogInterface dialogInterface, int i) {
  901. activity.finish();
  902. }
  903. })
  904. .create();
  905. }
  906.  
  907. }
  908.  
  909. /**
  910. * Shows OK/Cancel confirmation dialog about camera permission.
  911. */
  912. public static class ConfirmationDialog extends DialogFragment {
  913.  
  914. @Override
  915. public Dialog onCreateDialog(Bundle savedInstanceState) {
  916. final Fragment parent = getParentFragment();
  917. return new AlertDialog.Builder(getActivity())
  918. .setMessage("This sample needs camera permission")
  919. .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
  920. @Override
  921. public void onClick(DialogInterface dialog, int which) {
  922. FragmentCompat.requestPermissions(parent,
  923. new String[]{Manifest.permission.CAMERA},
  924. REQUEST_CAMERA_PERMISSION);
  925. }
  926. })
  927. .setNegativeButton(android.R.string.cancel,
  928. new DialogInterface.OnClickListener() {
  929. @Override
  930. public void onClick(DialogInterface dialog, int which) {
  931. Activity activity = parent.getActivity();
  932. if (activity != null) {
  933. activity.finish();
  934. }
  935. }
  936. })
  937. .create();
  938. }
  939. }
  940.  
  941. }
Add Comment
Please, Sign In to add comment