notBigEnough = new ArrayList<>();
494 | int w = aspectRatio.getWidth();
495 | int h = aspectRatio.getHeight();
496 | for (Size option : choices) {
497 | if (option.getWidth() <= maxWidth && option.getHeight() <= maxHeight &&
498 | option.getHeight() == option.getWidth() * h / w) {
499 | if (option.getWidth() >= textureViewWidth &&
500 | option.getHeight() >= textureViewHeight) {
501 | bigEnough.add(option);
502 | } else {
503 | notBigEnough.add(option);
504 | }
505 | }
506 | }
507 |
508 | // 挑那些最小中的足够大的。如果没有足够大的,选择最大的那些不够大的。
509 | if (bigEnough.size() > 0) {
510 | return Collections.min(bigEnough, new CompareSizesByArea());
511 | } else if (notBigEnough.size() > 0) {
512 | return Collections.max(notBigEnough, new CompareSizesByArea());
513 | } else {
514 | Log.e(TAG, "Couldn't find any suitable preview size");
515 | return choices[0];
516 | }
517 | }
518 |
519 |
520 | /**
521 | * 设置与摄像机相关的成员变量。
522 | *
523 | * @param width 相机预览可用尺寸的宽度
524 | * @param height 相机预览可用尺寸的高度
525 | */
526 | @SuppressWarnings("SuspiciousNameCombination")
527 | private void setUpCameraOutputs(int width, int height) {
528 | CameraManager manager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
529 | try {
530 | String[] cameraIdList = manager.getCameraIdList();
531 | mCameraCount = cameraIdList.length;
532 | for (String cameraId : cameraIdList) {
533 | CameraCharacteristics characteristics
534 | = manager.getCameraCharacteristics(cameraId);
535 |
536 | //判断当前摄像头是前置还是后置摄像头
537 | Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
538 | if (facing != null && facing != mCurrentCameraFacing) {
539 | continue;
540 | }
541 |
542 | StreamConfigurationMap map = characteristics.get(
543 | CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
544 | if (map == null) {
545 | continue;
546 | }
547 |
548 | // 对于静态图像捕获,我们使用最大可用的大小。
549 | Size largest = Collections.max(
550 | Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
551 | new CompareSizesByArea());
552 | mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(),
553 | ImageFormat.JPEG, /*maxImages*/2);
554 | mImageReader.setOnImageAvailableListener(
555 | mOnImageAvailableListener, mBackgroundHandler);
556 |
557 | // 找出是否需要交换尺寸以获得相对与传感器坐标的预览大小
558 | int displayRotation = mWindowManager.getDefaultDisplay().getRotation();
559 | //检验条件
560 | mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
561 | boolean swappedDimensions = false;
562 | switch (displayRotation) {
563 | case Surface.ROTATION_0:
564 | case Surface.ROTATION_180:
565 | if (mSensorOrientation == 90 || mSensorOrientation == 270) {
566 | swappedDimensions = true;
567 | }
568 | break;
569 | case Surface.ROTATION_90:
570 | case Surface.ROTATION_270:
571 | if (mSensorOrientation == 0 || mSensorOrientation == 180) {
572 | swappedDimensions = true;
573 | }
574 | break;
575 | default:
576 | Log.e(TAG, "Display rotation is invalid: " + displayRotation);
577 | }
578 |
579 | Point displaySize = new Point();
580 | mWindowManager.getDefaultDisplay().getSize(displaySize);
581 | int rotatedPreviewWidth = width;
582 | int rotatedPreviewHeight = height;
583 | int maxPreviewWidth = displaySize.x;
584 | int maxPreviewHeight = displaySize.y;
585 |
586 | if (swappedDimensions) {
587 | rotatedPreviewWidth = height;
588 | rotatedPreviewHeight = width;
589 | maxPreviewWidth = displaySize.y;
590 | maxPreviewHeight = displaySize.x;
591 | }
592 |
593 | if (maxPreviewWidth > MAX_PREVIEW_WIDTH) {
594 | maxPreviewWidth = MAX_PREVIEW_WIDTH;
595 | }
596 |
597 | if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) {
598 | maxPreviewHeight = MAX_PREVIEW_HEIGHT;
599 | }
600 |
601 | // 危险,W.R.!尝试使用太大的预览大小可能超过相机总线的带宽限制,导致高清的预览,但存储垃圾捕获数据。
602 | mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
603 | rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
604 | maxPreviewHeight, largest);
605 |
606 | // 我们将TextureView的宽高比与我们选择的预览大小相匹配。
607 | int orientation = getResources().getConfiguration().orientation;
608 | if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
609 | setAspectRatio(
610 | mPreviewSize.getWidth(), mPreviewSize.getHeight());
611 | } else {
612 | setAspectRatio(
613 | mPreviewSize.getHeight(), mPreviewSize.getWidth());
614 | }
615 |
616 | //检验是否支持flash
617 | Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
618 | mFlashSupported = available == null ? false : available;
619 |
620 | mCameraId = cameraId;
621 | return;
622 | }
623 | } catch (CameraAccessException e) {
624 | e.printStackTrace();
625 | } catch (NullPointerException e) {
626 | //抛出空指针一般代表当前设备不支持Camera2API
627 | Log.e(TAG, "This device doesn't support Camera2 API.");
628 |
629 | }
630 | }
631 |
632 | /**
633 | * 打开指定的相机(mCameraId)
634 | */
635 | private void openCamera(int width, int height) {
636 |
637 | setUpCameraOutputs(width, height);
638 | configureTransform(width, height);
639 |
640 | CameraManager manager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
641 | try {
642 | if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
643 | throw new RuntimeException("Time out waiting to lock camera1 opening.");
644 | }
645 | if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
646 | return;
647 | }
648 | manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
649 | } catch (CameraAccessException e) {
650 | e.printStackTrace();
651 | } catch (InterruptedException e) {
652 | throw new RuntimeException("Interrupted while trying to lock camera1 opening.", e);
653 | }
654 | }
655 |
656 | /**
657 | * 关闭相机
658 | */
659 | private void closeCamera() {
660 | try {
661 | mCameraOpenCloseLock.acquire();
662 | if (null != mCaptureSession) {
663 | mCaptureSession.close();
664 | mCaptureSession = null;
665 | }
666 | if (null != mCameraDevice) {
667 | mCameraDevice.close();
668 | mCameraDevice = null;
669 | }
670 | if (null != mImageReader) {
671 | mImageReader.close();
672 | mImageReader = null;
673 | }
674 | } catch (InterruptedException e) {
675 | throw new RuntimeException("Interrupted while trying to lock camera1 closing.", e);
676 | } finally {
677 | mCameraOpenCloseLock.release();
678 | }
679 | }
680 |
681 | /**
682 | * 启动后台线程和Handler.
683 | */
684 | private void startBackgroundThread() {
685 | mBackgroundThread = new HandlerThread("CameraBackground");
686 | mBackgroundThread.start();
687 | mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
688 | }
689 |
690 | /**
691 | * 停止后台线程和Handler.
692 | */
693 | private void stopBackgroundThread() {
694 | mBackgroundThread.quitSafely();
695 | try {
696 | mBackgroundThread.join();
697 | mBackgroundThread = null;
698 | mBackgroundHandler = null;
699 | } catch (InterruptedException e) {
700 | e.printStackTrace();
701 | }
702 | }
703 |
704 | /**
705 | * 创建一个新的 {@link CameraCaptureSession} 用于相机预览.
706 | */
707 | private void createCameraPreviewSession() {
708 | try {
709 | SurfaceTexture texture = getSurfaceTexture();
710 | assert texture != null;
711 |
712 | // 我们将默认缓冲区的大小设置为我们想要的相机预览的大小。
713 | texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
714 |
715 | // 我们需要开始预览输出Surface
716 | Surface surface = new Surface(texture);
717 |
718 | // 我们建立了一个具有输出Surface的捕获器。
719 | mPreviewRequestBuilder
720 | = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
721 | mPreviewRequestBuilder.addTarget(surface);
722 |
723 | // 这里,我们创建了一个用于相机预览的CameraCaptureSession
724 | mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
725 | new CameraCaptureSession.StateCallback() {
726 |
727 | @Override
728 | public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
729 | // 相机已经关闭
730 | if (null == mCameraDevice) {
731 | return;
732 | }
733 |
734 | // 当session准备好后,我们开始显示预览
735 | mCaptureSession = cameraCaptureSession;
736 | try {
737 | // 相机预览时应连续自动对焦
738 | mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
739 | CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
740 | // 设置闪光灯在必要时自动打开
741 | setAutoFlash(mPreviewRequestBuilder);
742 |
743 | // 最终,显示相机预览
744 | mPreviewRequest = mPreviewRequestBuilder.build();
745 | mCaptureSession.setRepeatingRequest(mPreviewRequest,
746 | mCaptureCallback, mBackgroundHandler);
747 | } catch (CameraAccessException e) {
748 | e.printStackTrace();
749 | }
750 | }
751 |
752 | @Override
753 | public void onConfigureFailed(
754 | @NonNull CameraCaptureSession cameraCaptureSession) {
755 | Log.e(TAG, "CameraCaptureSession.StateCallback onConfigureFailed");
756 | }
757 | }, null
758 | );
759 | } catch (CameraAccessException e) {
760 | e.printStackTrace();
761 | }
762 | }
763 |
764 | /**
765 | * 配置必要的 {@link android.graphics.Matrix} 转换为 `mTextureView`.
766 | *
767 | * 该方法应该在setUpCameraOutputs中确定相机预览大小以及“mTextureView”的大小固定之后调用。
768 | *
769 | * @param viewWidth The width of `mTextureView`
770 | * @param viewHeight The height of `mTextureView`
771 | */
772 | private void configureTransform(int viewWidth, int viewHeight) {
773 | if (null == mPreviewSize || null == mContext) {
774 | return;
775 | }
776 |
777 | int rotation = mWindowManager.getDefaultDisplay().getRotation();
778 | Matrix matrix = new Matrix();
779 | RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
780 | RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
781 | float centerX = viewRect.centerX();
782 | float centerY = viewRect.centerY();
783 | if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
784 | bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
785 | matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
786 | float scale = Math.max(
787 | (float) viewHeight / mPreviewSize.getHeight(),
788 | (float) viewWidth / mPreviewSize.getWidth());
789 | matrix.postScale(scale, scale, centerX, centerY);
790 | matrix.postRotate(90 * (rotation - 2), centerX, centerY);
791 | } else if (Surface.ROTATION_180 == rotation) {
792 | matrix.postRotate(180, centerX, centerY);
793 | }
794 | setTransform(matrix);
795 | }
796 |
797 |
798 | /**
799 | * 锁定焦点作为静态图像捕获的第一步
800 | */
801 | private void lockFocus() {
802 | try {
803 | // 这里是让相机锁定焦点
804 | mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
805 | CameraMetadata.CONTROL_AF_TRIGGER_START);
806 | // 告知 #mCaptureCallback 等待锁
807 | mState = STATE_WAITING_LOCK;
808 | mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
809 | mBackgroundHandler);
810 | } catch (CameraAccessException e) {
811 | e.printStackTrace();
812 | }
813 | }
814 |
815 | /**
816 | * 运行预捕获序列捕获一张静态图片。
817 | *
818 | * 这个方法应该在我们从得到mCaptureCallback的响应后调用
819 | */
820 | private void runPrecaptureSequence() {
821 | try {
822 | // 这就是如何告诉相机触发。
823 | mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
824 | CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START);
825 | // 告知 #mCaptureCallback 等待设置预捕获序列。
826 | mState = STATE_WAITING_PRECAPTURE;
827 | mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
828 | mBackgroundHandler);
829 | } catch (CameraAccessException e) {
830 | e.printStackTrace();
831 | }
832 | }
833 |
834 | /**
835 | * 捕获一张静态图片
836 | * 这个方法应该在我们从得到mCaptureCallback的响应后调用
837 | */
838 | private void captureStillPicture() {
839 | try {
840 | if (null == mCameraDevice) {
841 | return;
842 | }
843 | // 这是 CaptureRequest.Builder ,我们用它来进行拍照
844 | final CaptureRequest.Builder captureBuilder =
845 | mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
846 | captureBuilder.addTarget(mImageReader.getSurface());
847 |
848 | // 使用相同的AE和AF模式作为预览。
849 | captureBuilder.set(CaptureRequest.CONTROL_AF_MODE,
850 | CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
851 | setAutoFlash(captureBuilder);
852 |
853 | // 方向
854 | int rotation = mWindowManager.getDefaultDisplay().getRotation();
855 | captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getOrientation(rotation));
856 |
857 | CameraCaptureSession.CaptureCallback CaptureCallback
858 | = new CameraCaptureSession.CaptureCallback() {
859 |
860 | @Override
861 | public void onCaptureCompleted(@NonNull CameraCaptureSession session,
862 | @NonNull CaptureRequest request,
863 | @NonNull TotalCaptureResult result) {
864 | Log.d(TAG, "CameraCaptureSession.CaptureCallback onCaptureCompleted 图片保存地址为:" + mPictureFile.toString());
865 | if (mTakePictureCallback != null) {
866 | mTakePictureCallback.success(mPictureFile.getAbsolutePath());
867 | }
868 | unlockFocus();
869 | }
870 | };
871 |
872 | mCaptureSession.stopRepeating();
873 | mCaptureSession.abortCaptures();
874 | mCaptureSession.capture(captureBuilder.build(), CaptureCallback, null);
875 | } catch (CameraAccessException e) {
876 | e.printStackTrace();
877 | }
878 | }
879 |
880 | /**
881 | * 从指定的屏幕旋转中检索JPEG方向。
882 | *
883 | * @param rotation 图片旋转
884 | * @return The JPEG orientation (one of 0, 90, 270, and 360)
885 | */
886 | private int getOrientation(int rotation) {
887 | // 对于大多数设备,传感器定向是90,对于某些设备(例如Nexus 5X)是270。
888 | //我们必须考虑到这一点,并适当的旋转JPEG。
889 | //对于取向为90的设备,我们只需从方向返回映射即可。
890 | //对于方向为270的设备,我们需要旋转JPEG 180度。
891 | return (ORIENTATIONS.get(rotation) + mSensorOrientation + 270) % 360;
892 | }
893 |
894 | /**
895 | * 解锁焦点.
896 | *
897 | * 此方法应该在静态图片捕获序列结束后调用
898 | */
899 | private void unlockFocus() {
900 | try {
901 | // 重置自动对焦触发
902 | mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
903 | CameraMetadata.CONTROL_AF_TRIGGER_CANCEL);
904 | setAutoFlash(mPreviewRequestBuilder);
905 | mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
906 | mBackgroundHandler);
907 | // 在此之后,相机将回到正常的预览状态。
908 | mState = STATE_PREVIEW;
909 | mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback,
910 | mBackgroundHandler);
911 | } catch (CameraAccessException e) {
912 | e.printStackTrace();
913 | }
914 | }
915 |
916 |
917 | private void setAutoFlash(CaptureRequest.Builder requestBuilder) {
918 | if (mFlashSupported) {
919 | requestBuilder.set(CaptureRequest.CONTROL_AE_MODE,
920 | CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
921 | }
922 | }
923 |
924 | /**
925 | * 将JPEG{@link Image}保存并放到指定的文件中
926 | */
927 | private static class ImageSaver implements Runnable {
928 |
929 | /**
930 | * The JPEG image
931 | */
932 | private final Image mImage;
933 | /**
934 | * The file we save the image into.
935 | */
936 | private final File mFile;
937 |
938 | ImageSaver(Image image, File file) {
939 | mImage = image;
940 | mFile = file;
941 | }
942 |
943 | @Override
944 | public void run() {
945 | ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
946 | byte[] bytes = new byte[buffer.remaining()];
947 | buffer.get(bytes);
948 | FileOutputStream output = null;
949 | try {
950 | output = new FileOutputStream(mFile);
951 | output.write(bytes);
952 | } catch (IOException e) {
953 | e.printStackTrace();
954 | } finally {
955 | mImage.close();
956 | if (null != output) {
957 | try {
958 | output.close();
959 | } catch (IOException e) {
960 | e.printStackTrace();
961 | }
962 | }
963 | }
964 | }
965 |
966 | }
967 |
968 | /**
969 | * 根据它们的区域比较两个的大小 {@code Size}。
970 | */
971 | static class CompareSizesByArea implements Comparator {
972 |
973 | @Override
974 | public int compare(Size lhs, Size rhs) {
975 | // We cast here to ensure the multiplications won't overflow
976 | return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
977 | (long) rhs.getWidth() * rhs.getHeight());
978 | }
979 |
980 | }
981 |
982 |
983 | }
984 |
--------------------------------------------------------------------------------
/app/src/main/java/com/linkin/camera2examples/camera/CameraView.java:
--------------------------------------------------------------------------------
1 | package com.linkin.camera2examples.camera;
2 |
3 | /**
4 | * Author: Linkin
5 | * Time:2018/8/29
6 | * Email:liuzhongjun@novel-supertv.com
7 | * Blog:https://blog.csdn.net/Android_Technology
8 | * Desc: TODO
9 | */
10 |
11 | public interface CameraView {
12 |
13 | /**
14 | * 与生命周期onResume调用
15 | */
16 | void onResume();
17 |
18 | /**
19 | * 与生命周期onPause调用
20 | */
21 | void onPause();
22 |
23 | /**
24 | * 拍照
25 | */
26 | void takePicture();
27 |
28 | /**
29 | * 拍照(有回调)
30 | */
31 | void takePicture(TakePictureCallback takePictureCallback);
32 |
33 | /**
34 | * 设置保存的图片文件
35 | *
36 | * @param pictureSavePath 拍摄的图片返回的绝对路径
37 | */
38 | void setPictureSavePath(String pictureSavePath);
39 |
40 | /**
41 | * 切换相机摄像头
42 | */
43 | void switchCameraFacing();
44 |
45 |
46 | interface TakePictureCallback {
47 |
48 | void success(String picturePath);
49 |
50 | void error(final String error);
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/app/src/main/java/com/linkin/camera2examples/util/DeviceUtils.java:
--------------------------------------------------------------------------------
1 | package com.linkin.camera2examples.util;
2 |
3 | import android.content.Context;
4 | import android.content.pm.PackageManager;
5 |
6 | /**
7 | * Author: Linkin
8 | * Time:2018/8/27
9 | * Email:liuzhongjun@novel-supertv.com
10 | * Blog:https://blog.csdn.net/Android_Technology
11 | * Desc: 设备相关工具类
12 | */
13 |
14 | public final class DeviceUtils {
15 |
16 | /**
17 | * 检验设备是否有摄像头
18 | */
19 | public static boolean checkCameraHardware(Context context) {
20 | if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
21 | // this device has a camera1
22 | return true;
23 | } else {
24 | // no camera1 on this device
25 | return false;
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/app/src/main/java/com/linkin/camera2examples/util/FileUtils.java:
--------------------------------------------------------------------------------
1 | package com.linkin.camera2examples.util;
2 |
3 | import android.content.Context;
4 | import android.os.Environment;
5 | import android.util.Log;
6 |
7 | import java.io.File;
8 | import java.text.SimpleDateFormat;
9 | import java.util.Date;
10 |
11 | /**
12 | * Author: Linkin
13 | * Time:2018/8/27
14 | * Email:liuzhongjun@novel-supertv.com
15 | * Blog:https://blog.csdn.net/Android_Technology
16 | * Desc: TODO
17 | */
18 |
19 | public class FileUtils {
20 |
21 | private static final String TAG = "FileUtils";
22 |
23 | /**
24 | * 检测外部存储是否存在
25 | */
26 | public static boolean checkSDCard() {
27 | return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
28 | }
29 |
30 |
31 | public static final int MEDIA_TYPE_IMAGE = 1;
32 | public static final int MEDIA_TYPE_VIDEO = 2;
33 |
34 | /**
35 | * 创建一个文件来保存图片或者视频
36 | */
37 | public static File getOutputMediaFile(Context mContext, int type) {
38 |
39 | File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
40 | Environment.DIRECTORY_PICTURES), "Camera2Examples");
41 |
42 | // This location works best if you want the created images to be shared
43 | // between applications and persist after your app has been uninstalled.
44 |
45 | // Create the storage directory if it does not exist
46 | if (!mediaStorageDir.exists()) {
47 | if (!mediaStorageDir.mkdirs()) {
48 | Log.d(TAG, "failed to create directory");
49 | return null;
50 | }
51 | }
52 |
53 | // Create a media file name
54 | String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
55 | File mediaFile;
56 | if (type == MEDIA_TYPE_IMAGE) {
57 | mediaFile = new File(mediaStorageDir.getPath() + File.separator +
58 | "IMG_" + timeStamp + ".jpg");
59 | } else if (type == MEDIA_TYPE_VIDEO) {
60 | mediaFile = new File(mediaStorageDir.getPath() + File.separator +
61 | "VID_" + timeStamp + ".mp4");
62 | } else {
63 | return null;
64 | }
65 | return mediaFile;
66 | }
67 |
68 |
69 | public static File getTimeStampMediaFile(String parentPath, int type) {
70 | // Create a media file name
71 | String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
72 | File mediaFile;
73 | if (type == MEDIA_TYPE_IMAGE) {
74 | mediaFile = new File(parentPath + File.separator +
75 | "IMG_" + timeStamp + ".jpg");
76 | } else if (type == MEDIA_TYPE_VIDEO) {
77 | mediaFile = new File(parentPath + File.separator +
78 | "VID_" + timeStamp + ".mp4");
79 | } else {
80 | return null;
81 | }
82 | return mediaFile;
83 | }
84 |
85 | }
86 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/camera.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gentleman-jun/Camera2Examples/0c6875c6fc37b271f43b14010db30ddccd97f01b/app/src/main/res/drawable-hdpi/camera.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/switch_camera.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gentleman-jun/Camera2Examples/0c6875c6fc37b271f43b14010db30ddccd97f01b/app/src/main/res/drawable-hdpi/switch_camera.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/camera1.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gentleman-jun/Camera2Examples/0c6875c6fc37b271f43b14010db30ddccd97f01b/app/src/main/res/drawable-xxxhdpi/camera1.jpg
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/camera2.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gentleman-jun/Camera2Examples/0c6875c6fc37b271f43b14010db30ddccd97f01b/app/src/main/res/drawable-xxxhdpi/camera2.jpg
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_camera_show.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
11 |
12 |
13 |
14 |
15 |
22 |
23 |
31 |
32 |
33 |
41 |
42 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
19 |
20 |
26 |
27 |
38 |
39 |
50 |
51 |
52 |
53 |
54 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gentleman-jun/Camera2Examples/0c6875c6fc37b271f43b14010db30ddccd97f01b/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gentleman-jun/Camera2Examples/0c6875c6fc37b271f43b14010db30ddccd97f01b/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gentleman-jun/Camera2Examples/0c6875c6fc37b271f43b14010db30ddccd97f01b/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gentleman-jun/Camera2Examples/0c6875c6fc37b271f43b14010db30ddccd97f01b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gentleman-jun/Camera2Examples/0c6875c6fc37b271f43b14010db30ddccd97f01b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #47ac94
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Camera2Examples
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.3.3'
9 |
10 | // NOTE: Do not place your application dependencies here; they belong
11 | // in the individual module build.gradle files
12 | }
13 | }
14 |
15 | allprojects {
16 | repositories {
17 | jcenter()
18 | }
19 | }
20 |
21 | task clean(type: Delete) {
22 | delete rootProject.buildDir
23 | }
24 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gentleman-jun/Camera2Examples/0c6875c6fc37b271f43b14010db30ddccd97f01b/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Aug 09 15:26:40 CST 2018
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------