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