This article shares the specific code displayed in the Android Camera2 implementation preview box for your reference. The specific content is as follows
The interface of Camer2 to preview Android is slightly more complicated than Camera1, but it is not difficult. Below is a simple preview related code.
1. First, add permissions
<uses-permission android:name=""/>
2. Create an XML containing control TextureView
For example activity_main.xml:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:andro android:layout_width="match_parent" android:layout_height="match_parent"> <TextureView android: android:layout_width="match_parent" android:layout_height="match_parent" /> <Button android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="0.8dp" android:text="stop preview" android:layout_alignParentBottom="true" android:layout_alignParentEnd="true"/> <Button android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="0.8dp" android:text="start preview" android:layout_alignParentBottom="true" android:layout_toStartOf="@id/btnStop"/> </RelativeLayout>
3. Create and use CamaerManager in Activity
(1) Use (), pass in to listen for openState status
(2) Execute the preview interface in the openState state
(3) Just release the object when closing the preview box
For example, the following code:
package ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import .; import .; import .; import .; import .; import .; import .; import .; import .; import .; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; /** * This class uses Camera2 to use a simple camera */ public class MainActivity2 extends AppCompatActivity implements { private static final String TAG = "Camera2Test"; private static final int REQUEST_CAMERA_PERMISSION = 80; private TextureView mTextureView; private Button mBtnStart; private Button mBtnStop; private CameraManager mCameraManager; private CameraDevice mCameraDevice; private String mCameraId = "0"; private Size previewSize; // Used to set the width and height of the preview @Override protected void onCreate(Bundle savedInstanceState) { (savedInstanceState); (TAG, "onCreate!"); setContentView(.activity_main); initData(); intiView(); initEvent(); } private void intiView() { mTextureView = (TextureView) findViewById(); mBtnStart = (Button) findViewById(); mBtnStop = (Button) findViewById(); } private void initData() { mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); if (mCameraManager == null) { (this, "CameraService object cannot be obtained!", Toast.LENGTH_LONG).show(); finish(); } } private void initEvent() { (this); (this); // Listen to the status of the preview view (new () { @Override public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) { (TAG, "onSurfaceTextureAvailable width = " + width + ",height = " + height); //1. When SurefaceTexture is available, set the camera parameters and turn on the camera initCamera(); } @Override public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) { (TAG, "onSurfaceTextureSizeChanged width = " + width + ",height = " + height); } @Override public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) { (TAG, "onSurfaceTextureDestroyed!"); return false; } @Override public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) { //When you preview normally, you will keep printing //(TAG, "onSurfaceTextureUpdated!"); } }); } private void initCamera() { (TAG, "initCamera"); // 2. Configure the front camera to get the size and id getCameraIdAndPreviewSizeByFacing(CameraCharacteristics.LENS_FACING_FRONT); // 0 is the front camera, and 0 is defined in Camera api1 as the rear camera // 3. Turn on the camera openCamera(); } /*Get the best size for cameraId and camera preview*/ private void getCameraIdAndPreviewSizeByFacing(int lensFacingFront) { (TAG, "getCameraIdAndPreviewSizeByFacing"); try { String[] cameraIdList = (); //If the device node is not available, it will block here (TAG, "getCameraIdAndPreviewSizeByFacing cameraIdList = " + (cameraIdList)); for (String cameraId : cameraIdList) { CameraCharacteristics cameraCharacteristics = (cameraId); int deviceLevel = (CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL); //The compatibility between hardware and API2, 0-4 (TAG, "deviceLevel = " + deviceLevel); int facing = (CameraCharacteristics.LENS_FACING); if (facing != lensFacingFront) { continue; } StreamConfigurationMap streamConfigurationMap = (CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); Size[] outputSizes = (); mCameraId = cameraId; previewSize = setOptimalPreviewSize(outputSizes, (), ()); (TAG, "Best preview size (w-h):" + () + "-" + () + ",Camera id:" + mCameraId); } } catch (CameraAccessException e) { (TAG, "getCameraIdAndPreviewSizeByFacing error = " + ()); } } /** * Turn on the camera, the preview is executed in the callback. */ private void openCamera() { try { // 4. Permission check if ((this, ) != PackageManager.PERMISSION_GRANTED) { requestCameraPermission(); return; } // 5. Really turn on the camera (TAG, "openCamera"); (mCameraId, mStateCallback, null); } catch (CameraAccessException e) { (TAG, "openCamera error = " + ()); } } //Request camera permission private void requestCameraPermission() { requestPermissions(new String[]{}, REQUEST_CAMERA_PERMISSION); } /** * Select the closest preview size based on the available preview size of the camera and the display size of the user-designated TextureView */ private Size setOptimalPreviewSize(Size[] sizes, int previewViewWidth, int previewViewHeight) { List<Size> bigEnoughSizes = new ArrayList<>(); List<Size> notBigEnoughSizes = new ArrayList<>(); for (Size size : sizes) { if (() >= previewViewWidth && () >= previewViewHeight) { (size); } else { (size); } } if (() > 0) { return (bigEnoughSizes, new Comparator<Size>() { @Override public int compare(Size lhs, Size rhs) { return ((long) () * () - (long) () * ()); } }); } else if (() > 0) { return (notBigEnoughSizes, new Comparator<Size>() { @Override public int compare(Size lhs, Size rhs) { return ((long) () * () - (long) () * ()); } }); } else { (TAG, "No suitable preview size found"); return sizes[0]; } } //Change the camera and release the object private void releaseCamera() { if (mCameraDevice != null) { (); mCameraDevice = null; } } /** * Camera status monitor object */ private final mStateCallback = new () { @Override public void onOpened(CameraDevice camera) { (TAG, "StateCallback! onOpened"); mCameraDevice = camera; // Open successfully, save the CameraDevice instance representing the camera SurfaceTexture surfaceTexture = (); ((), ()); Surface surface = new Surface(surfaceTexture); ArrayList<Surface> previewList = new ArrayList<>(); (surface); try { // 6. Pass the surface of the TextureView to the CameraDevice (previewList, new () { @Override public void onConfigured(@NonNull CameraCaptureSession session) { try { builder = (CameraDevice.TEMPLATE_PREVIEW); (surface); // It must be set to preview normally CaptureRequest captureRequest = (); // Bind with CaptureRequest (this is the last step, the camera preview is available) (captureRequest, mSessionCaptureCallback, null); } catch (CameraAccessException e) { (TAG, "createCaptureRequest error = " + ()); } } @Override public void onConfigureFailed(@NonNull CameraCaptureSession session) { (TAG, "onConfigureFailed"); } }, null); } catch (CameraAccessException e) { (TAG, "createCaptureSession error = " + ()); } } @Override public void onDisconnected(@NonNull CameraDevice camera) { (TAG, "StateCallback! onDisconnected () = " + ()); releaseCamera(); } @Override public void onError(@NonNull CameraDevice camera, int error) { (TAG, "StateCallback () = " + () + " , error = " + error); releaseCamera(); } }; //Preview situation callback private mSessionCaptureCallback = new () { @Override public void onCaptureStarted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, long timestamp, long frameNumber) { (session, request, timestamp, frameNumber); // The normal preview will be refreshed //(TAG, "mSessionCaptureCallback onCaptureStarted frameNumber =" + frameNumber); } @Override public void onCaptureProgressed(CameraCaptureSession session, CaptureRequest request, CaptureResult partialResult) { (session, request, partialResult); (TAG, "mSessionCaptureCallback onCaptureProgressed request =" + request); } @Override public void onCaptureFailed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureFailure failure) { (session, request, failure); (TAG, "mSessionCaptureCallback onCaptureFailed request =" + request); } @Override public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) { (session, request, result); // It will be refreshed during normal preview //(TAG, "mSessionCaptureCallback onCaptureCompleted request =" + request); } }; @Override public void onClick(View v) { switch (()) { case : (TAG, "btnStart!"); openCamera(); break; case : (TAG, "btnStop!"); releaseCamera(); break; default: } } @Override protected void onDestroy() { (); releaseCamera(); } }
Camera1 is easier to use, but Camera1 will have less new features.
Simple use of Camaera1:Android Camera1 implements preview box display
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.