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.os.Message; 47 import android.util.Log; 48 import android.util.Size; 49 import android.util.SparseIntArray; 50 import android.view.LayoutInflater; 51 import android.view.Surface; 52 import android.view.TextureView; 53 import android.view.View; 54 import android.view.ViewGroup; 55 import android.widget.Toast; 56 57 import java.io.File; 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 Integer afState = result.get(CaptureResult.CONTROL_AF_STATE); 267 if (afState == null) { 268 captureStillPicture(); 269 } else if (CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED == afState || 270 CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED == afState) { 271 // CONTROL_AE_STATE can be null on some devices 272 Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE); 273 if (aeState == null || 274 aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED) { 275 mState = STATE_PICTURE_TAKEN; 276 captureStillPicture(); 277 } else { 278 runPrecaptureSequence(); 279 } 280 } 281 break; 282 } 283 case STATE_WAITING_PRECAPTURE: { 284 // CONTROL_AE_STATE can be null on some devices 285 Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE); 286 if (aeState == null || 287 aeState == CaptureResult.CONTROL_AE_STATE_PRECAPTURE || 288 aeState == CaptureRequest.CONTROL_AE_STATE_FLASH_REQUIRED) { 289 mState = STATE_WAITING_NON_PRECAPTURE; 290 } 291 break; 292 } 293 case STATE_WAITING_NON_PRECAPTURE: { 294 // CONTROL_AE_STATE can be null on some devices 295 Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE); 296 if (aeState == null || aeState != CaptureResult.CONTROL_AE_STATE_PRECAPTURE) { 297 mState = STATE_PICTURE_TAKEN; 298 captureStillPicture(); 299 } 300 break; 301 } 302 } 303 } 304 305 @Override 306 public void onCaptureProgressed(CameraCaptureSession session, CaptureRequest request, 307 CaptureResult partialResult) { 308 process(partialResult); 309 } 310 311 @Override 312 public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, 313 TotalCaptureResult result) { 314 process(result); 315 } 316 317 }; 318 319 /** 320 * A {@link Handler} for showing {@link Toast}s. 321 */ 322 private Handler mMessageHandler = new Handler() { 323 @Override 324 public void handleMessage(Message msg) { 325 Activity activity = getActivity(); 326 if (activity != null) { 327 Toast.makeText(activity, (String) msg.obj, Toast.LENGTH_SHORT).show(); 328 } 329 } 330 }; 331 332 /** 333 * Shows a {@link Toast} on the UI thread. 334 * 335 * @param text The message to show 336 */ showToast(String text)337 private void showToast(String text) { 338 // We show a Toast by sending request message to mMessageHandler. This makes sure that the 339 // Toast is shown on the UI thread. 340 Message message = Message.obtain(); 341 message.obj = text; 342 mMessageHandler.sendMessage(message); 343 } 344 345 /** 346 * Given {@code choices} of {@code Size}s supported by a camera, chooses the smallest one whose 347 * width and height are at least as large as the respective requested values, and whose aspect 348 * ratio matches with the specified value. 349 * 350 * @param choices The list of sizes that the camera supports for the intended output class 351 * @param width The minimum desired width 352 * @param height The minimum desired height 353 * @param aspectRatio The aspect ratio 354 * @return The optimal {@code Size}, or an arbitrary one if none were big enough 355 */ chooseOptimalSize(Size[] choices, int width, int height, Size aspectRatio)356 private static Size chooseOptimalSize(Size[] choices, int width, int height, Size aspectRatio) { 357 // Collect the supported resolutions that are at least as big as the preview Surface 358 List<Size> bigEnough = new ArrayList<Size>(); 359 int w = aspectRatio.getWidth(); 360 int h = aspectRatio.getHeight(); 361 for (Size option : choices) { 362 if (option.getHeight() == option.getWidth() * h / w && 363 option.getWidth() >= width && option.getHeight() >= height) { 364 bigEnough.add(option); 365 } 366 } 367 368 // Pick the smallest of those, assuming we found any 369 if (bigEnough.size() > 0) { 370 return Collections.min(bigEnough, new CompareSizesByArea()); 371 } else { 372 Log.e(TAG, "Couldn't find any suitable preview size"); 373 return choices[0]; 374 } 375 } 376 newInstance()377 public static Camera2BasicFragment newInstance() { 378 Camera2BasicFragment fragment = new Camera2BasicFragment(); 379 fragment.setRetainInstance(true); 380 return fragment; 381 } 382 383 @Override onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)384 public View onCreateView(LayoutInflater inflater, ViewGroup container, 385 Bundle savedInstanceState) { 386 return inflater.inflate(R.layout.fragment_camera2_basic, container, false); 387 } 388 389 @Override onViewCreated(final View view, Bundle savedInstanceState)390 public void onViewCreated(final View view, Bundle savedInstanceState) { 391 view.findViewById(R.id.picture).setOnClickListener(this); 392 view.findViewById(R.id.info).setOnClickListener(this); 393 mTextureView = (AutoFitTextureView) view.findViewById(R.id.texture); 394 } 395 396 @Override onActivityCreated(Bundle savedInstanceState)397 public void onActivityCreated(Bundle savedInstanceState) { 398 super.onActivityCreated(savedInstanceState); 399 mFile = new File(getActivity().getExternalFilesDir(null), "pic.jpg"); 400 } 401 402 @Override onResume()403 public void onResume() { 404 super.onResume(); 405 startBackgroundThread(); 406 407 // When the screen is turned off and turned back on, the SurfaceTexture is already 408 // available, and "onSurfaceTextureAvailable" will not be called. In that case, we can open 409 // a camera and start preview from here (otherwise, we wait until the surface is ready in 410 // the SurfaceTextureListener). 411 if (mTextureView.isAvailable()) { 412 openCamera(mTextureView.getWidth(), mTextureView.getHeight()); 413 } else { 414 mTextureView.setSurfaceTextureListener(mSurfaceTextureListener); 415 } 416 } 417 418 @Override onPause()419 public void onPause() { 420 closeCamera(); 421 stopBackgroundThread(); 422 super.onPause(); 423 } 424 425 /** 426 * Sets up member variables related to camera. 427 * 428 * @param width The width of available size for camera preview 429 * @param height The height of available size for camera preview 430 */ setUpCameraOutputs(int width, int height)431 private void setUpCameraOutputs(int width, int height) { 432 Activity activity = getActivity(); 433 CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); 434 try { 435 for (String cameraId : manager.getCameraIdList()) { 436 CameraCharacteristics characteristics 437 = manager.getCameraCharacteristics(cameraId); 438 439 // We don't use a front facing camera in this sample. 440 if (characteristics.get(CameraCharacteristics.LENS_FACING) 441 == CameraCharacteristics.LENS_FACING_FRONT) { 442 continue; 443 } 444 445 StreamConfigurationMap map = characteristics.get( 446 CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); 447 448 // For still image captures, we use the largest available size. 449 Size largest = Collections.max( 450 Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)), 451 new CompareSizesByArea()); 452 mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(), 453 ImageFormat.JPEG, /*maxImages*/2); 454 mImageReader.setOnImageAvailableListener( 455 mOnImageAvailableListener, mBackgroundHandler); 456 457 // Danger, W.R.! Attempting to use too large a preview size could exceed the camera 458 // bus' bandwidth limitation, resulting in gorgeous previews but the storage of 459 // garbage capture data. 460 mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), 461 width, height, largest); 462 463 // We fit the aspect ratio of TextureView to the size of preview we picked. 464 int orientation = getResources().getConfiguration().orientation; 465 if (orientation == Configuration.ORIENTATION_LANDSCAPE) { 466 mTextureView.setAspectRatio( 467 mPreviewSize.getWidth(), mPreviewSize.getHeight()); 468 } else { 469 mTextureView.setAspectRatio( 470 mPreviewSize.getHeight(), mPreviewSize.getWidth()); 471 } 472 473 mCameraId = cameraId; 474 return; 475 } 476 } catch (CameraAccessException e) { 477 e.printStackTrace(); 478 } catch (NullPointerException e) { 479 // Currently an NPE is thrown when the Camera2API is used but not supported on the 480 // device this code runs. 481 new ErrorDialog().show(getFragmentManager(), "dialog"); 482 } 483 } 484 485 /** 486 * Opens the camera specified by {@link Camera2BasicFragment#mCameraId}. 487 */ openCamera(int width, int height)488 private void openCamera(int width, int height) { 489 setUpCameraOutputs(width, height); 490 configureTransform(width, height); 491 Activity activity = getActivity(); 492 CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); 493 try { 494 if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) { 495 throw new RuntimeException("Time out waiting to lock camera opening."); 496 } 497 manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler); 498 } catch (CameraAccessException e) { 499 e.printStackTrace(); 500 } catch (InterruptedException e) { 501 throw new RuntimeException("Interrupted while trying to lock camera opening.", e); 502 } 503 } 504 505 /** 506 * Closes the current {@link CameraDevice}. 507 */ closeCamera()508 private void closeCamera() { 509 try { 510 mCameraOpenCloseLock.acquire(); 511 if (null != mCaptureSession) { 512 mCaptureSession.close(); 513 mCaptureSession = null; 514 } 515 if (null != mCameraDevice) { 516 mCameraDevice.close(); 517 mCameraDevice = null; 518 } 519 if (null != mImageReader) { 520 mImageReader.close(); 521 mImageReader = null; 522 } 523 } catch (InterruptedException e) { 524 throw new RuntimeException("Interrupted while trying to lock camera closing.", e); 525 } finally { 526 mCameraOpenCloseLock.release(); 527 } 528 } 529 530 /** 531 * Starts a background thread and its {@link Handler}. 532 */ startBackgroundThread()533 private void startBackgroundThread() { 534 mBackgroundThread = new HandlerThread("CameraBackground"); 535 mBackgroundThread.start(); 536 mBackgroundHandler = new Handler(mBackgroundThread.getLooper()); 537 } 538 539 /** 540 * Stops the background thread and its {@link Handler}. 541 */ stopBackgroundThread()542 private void stopBackgroundThread() { 543 mBackgroundThread.quitSafely(); 544 try { 545 mBackgroundThread.join(); 546 mBackgroundThread = null; 547 mBackgroundHandler = null; 548 } catch (InterruptedException e) { 549 e.printStackTrace(); 550 } 551 } 552 553 /** 554 * Creates a new {@link CameraCaptureSession} for camera preview. 555 */ createCameraPreviewSession()556 private void createCameraPreviewSession() { 557 try { 558 SurfaceTexture texture = mTextureView.getSurfaceTexture(); 559 assert texture != null; 560 561 // We configure the size of default buffer to be the size of camera preview we want. 562 texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight()); 563 564 // This is the output Surface we need to start preview. 565 Surface surface = new Surface(texture); 566 567 // We set up a CaptureRequest.Builder with the output Surface. 568 mPreviewRequestBuilder 569 = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); 570 mPreviewRequestBuilder.addTarget(surface); 571 572 // Here, we create a CameraCaptureSession for camera preview. 573 mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()), 574 new CameraCaptureSession.StateCallback() { 575 576 @Override 577 public void onConfigured(CameraCaptureSession cameraCaptureSession) { 578 // The camera is already closed 579 if (null == mCameraDevice) { 580 return; 581 } 582 583 // When the session is ready, we start displaying the preview. 584 mCaptureSession = cameraCaptureSession; 585 try { 586 // Auto focus should be continuous for camera preview. 587 mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, 588 CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE); 589 // Flash is automatically enabled when necessary. 590 mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, 591 CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH); 592 593 // Finally, we start displaying the camera preview. 594 mPreviewRequest = mPreviewRequestBuilder.build(); 595 mCaptureSession.setRepeatingRequest(mPreviewRequest, 596 mCaptureCallback, mBackgroundHandler); 597 } catch (CameraAccessException e) { 598 e.printStackTrace(); 599 } 600 } 601 602 @Override 603 public void onConfigureFailed(CameraCaptureSession cameraCaptureSession) { 604 showToast("Failed"); 605 } 606 }, null 607 ); 608 } catch (CameraAccessException e) { 609 e.printStackTrace(); 610 } 611 } 612 613 /** 614 * Configures the necessary {@link android.graphics.Matrix} transformation to `mTextureView`. 615 * This method should be called after the camera preview size is determined in 616 * setUpCameraOutputs and also the size of `mTextureView` is fixed. 617 * 618 * @param viewWidth The width of `mTextureView` 619 * @param viewHeight The height of `mTextureView` 620 */ configureTransform(int viewWidth, int viewHeight)621 private void configureTransform(int viewWidth, int viewHeight) { 622 Activity activity = getActivity(); 623 if (null == mTextureView || null == mPreviewSize || null == activity) { 624 return; 625 } 626 int rotation = activity.getWindowManager().getDefaultDisplay().getRotation(); 627 Matrix matrix = new Matrix(); 628 RectF viewRect = new RectF(0, 0, viewWidth, viewHeight); 629 RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth()); 630 float centerX = viewRect.centerX(); 631 float centerY = viewRect.centerY(); 632 if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) { 633 bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY()); 634 matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL); 635 float scale = Math.max( 636 (float) viewHeight / mPreviewSize.getHeight(), 637 (float) viewWidth / mPreviewSize.getWidth()); 638 matrix.postScale(scale, scale, centerX, centerY); 639 matrix.postRotate(90 * (rotation - 2), centerX, centerY); 640 } else if (Surface.ROTATION_180 == rotation) { 641 matrix.postRotate(180, centerX, centerY); 642 } 643 mTextureView.setTransform(matrix); 644 } 645 646 /** 647 * Initiate a still image capture. 648 */ takePicture()649 private void takePicture() { 650 lockFocus(); 651 } 652 653 /** 654 * Lock the focus as the first step for a still image capture. 655 */ lockFocus()656 private void lockFocus() { 657 try { 658 // This is how to tell the camera to lock focus. 659 mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, 660 CameraMetadata.CONTROL_AF_TRIGGER_START); 661 // Tell #mCaptureCallback to wait for the lock. 662 mState = STATE_WAITING_LOCK; 663 mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback, 664 mBackgroundHandler); 665 } catch (CameraAccessException e) { 666 e.printStackTrace(); 667 } 668 } 669 670 /** 671 * Run the precapture sequence for capturing a still image. This method should be called when we 672 * get a response in {@link #mCaptureCallback} from {@link #lockFocus()}. 673 */ runPrecaptureSequence()674 private void runPrecaptureSequence() { 675 try { 676 // This is how to tell the camera to trigger. 677 mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER, 678 CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START); 679 // Tell #mCaptureCallback to wait for the precapture sequence to be set. 680 mState = STATE_WAITING_PRECAPTURE; 681 mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback, 682 mBackgroundHandler); 683 } catch (CameraAccessException e) { 684 e.printStackTrace(); 685 } 686 } 687 688 /** 689 * Capture a still picture. This method should be called when we get a response in 690 * {@link #mCaptureCallback} from both {@link #lockFocus()}. 691 */ captureStillPicture()692 private void captureStillPicture() { 693 try { 694 final Activity activity = getActivity(); 695 if (null == activity || null == mCameraDevice) { 696 return; 697 } 698 // This is the CaptureRequest.Builder that we use to take a picture. 699 final CaptureRequest.Builder captureBuilder = 700 mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE); 701 captureBuilder.addTarget(mImageReader.getSurface()); 702 703 // Use the same AE and AF modes as the preview. 704 captureBuilder.set(CaptureRequest.CONTROL_AF_MODE, 705 CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE); 706 captureBuilder.set(CaptureRequest.CONTROL_AE_MODE, 707 CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH); 708 709 // Orientation 710 int rotation = activity.getWindowManager().getDefaultDisplay().getRotation(); 711 captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation)); 712 713 CameraCaptureSession.CaptureCallback CaptureCallback 714 = new CameraCaptureSession.CaptureCallback() { 715 716 @Override 717 public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, 718 TotalCaptureResult result) { 719 showToast("Saved: " + mFile); 720 unlockFocus(); 721 } 722 }; 723 724 mCaptureSession.stopRepeating(); 725 mCaptureSession.capture(captureBuilder.build(), CaptureCallback, null); 726 } catch (CameraAccessException e) { 727 e.printStackTrace(); 728 } 729 } 730 731 /** 732 * Unlock the focus. This method should be called when still image capture sequence is finished. 733 */ unlockFocus()734 private void unlockFocus() { 735 try { 736 // Reset the autofucos trigger 737 mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, 738 CameraMetadata.CONTROL_AF_TRIGGER_CANCEL); 739 mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, 740 CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH); 741 mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback, 742 mBackgroundHandler); 743 // After this, the camera will go back to the normal state of preview. 744 mState = STATE_PREVIEW; 745 mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback, 746 mBackgroundHandler); 747 } catch (CameraAccessException e) { 748 e.printStackTrace(); 749 } 750 } 751 752 @Override onClick(View view)753 public void onClick(View view) { 754 switch (view.getId()) { 755 case R.id.picture: { 756 takePicture(); 757 break; 758 } 759 case R.id.info: { 760 Activity activity = getActivity(); 761 if (null != activity) { 762 new AlertDialog.Builder(activity) 763 .setMessage(R.string.intro_message) 764 .setPositiveButton(android.R.string.ok, null) 765 .show(); 766 } 767 break; 768 } 769 } 770 } 771 772 /** 773 * Saves a JPEG {@link Image} into the specified {@link File}. 774 */ 775 private static class ImageSaver implements Runnable { 776 777 /** 778 * The JPEG image 779 */ 780 private final Image mImage; 781 /** 782 * The file we save the image into. 783 */ 784 private final File mFile; 785 ImageSaver(Image image, File file)786 public ImageSaver(Image image, File file) { 787 mImage = image; 788 mFile = file; 789 } 790 791 @Override run()792 public void run() { 793 ByteBuffer buffer = mImage.getPlanes()[0].getBuffer(); 794 byte[] bytes = new byte[buffer.remaining()]; 795 buffer.get(bytes); 796 FileOutputStream output = null; 797 try { 798 output = new FileOutputStream(mFile); 799 output.write(bytes); 800 } catch (IOException e) { 801 e.printStackTrace(); 802 } finally { 803 mImage.close(); 804 if (null != output) { 805 try { 806 output.close(); 807 } catch (IOException e) { 808 e.printStackTrace(); 809 } 810 } 811 } 812 } 813 814 } 815 816 /** 817 * Compares two {@code Size}s based on their areas. 818 */ 819 static class CompareSizesByArea implements Comparator<Size> { 820 821 @Override compare(Size lhs, Size rhs)822 public int compare(Size lhs, Size rhs) { 823 // We cast here to ensure the multiplications won't overflow 824 return Long.signum((long) lhs.getWidth() * lhs.getHeight() - 825 (long) rhs.getWidth() * rhs.getHeight()); 826 } 827 828 } 829 830 public static class ErrorDialog extends DialogFragment { 831 832 @Override onCreateDialog(Bundle savedInstanceState)833 public Dialog onCreateDialog(Bundle savedInstanceState) { 834 final Activity activity = getActivity(); 835 return new AlertDialog.Builder(activity) 836 .setMessage("This device doesn't support Camera2 API.") 837 .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { 838 @Override 839 public void onClick(DialogInterface dialogInterface, int i) { 840 activity.finish(); 841 } 842 }) 843 .create(); 844 } 845 846 } 847 848 } 849