Skip to content Skip to sidebar Skip to footer

Why Camera2 Api Working Not Correct?

I using code Camera2 API at: https://github.com/googlesamples/android-Camera2Basic. If i take picture time 1: afState =4, it is take picture ok. But if I take picture time 2: afSta

Solution 1:

THE FOLLOWING STEPS ARE TAKEN WHEN USING ANDROID CAMERA2 API

enter image description here

**Open the Manifest.xml **

<?xml version="1.0" encoding="utf-8"?><manifestxmlns:android="http://schemas.android.com/apk/res/android"package="com.inducesmile.androidcameraapi2"><uses-sdkandroid:minSdkVersion="21"android:targetSdkVersion="21" /><uses-permissionandroid:name="android.permission.CAMERA" /><uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-featureandroid:name="android.hardware.camera2.full" /><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:supportsRtl="true"android:theme="@style/AppTheme"><activityandroid:name=".AndroidCameraApi"><intent-filter><actionandroid:name="android.intent.action.MAIN" /><categoryandroid:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>

Open the main layout xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context="com.inducesmile.androidcameraapi2.AndroidCameraApi"><TextureViewandroid:id="@+id/texture"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_above="@+id/btn_takepicture"android:layout_alignParentTop="true"/><Buttonandroid:id="@+id/btn_takepicture"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:layout_centerHorizontal="true"android:layout_marginBottom="16dp"android:layout_marginTop="16dp"android:text="@string/take_picture" /></RelativeLayout>

Open Main java class

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
 import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
 import java.nio.ByteBuffer;
  import java.util.ArrayList;
  import java.util.Arrays;
  import java.util.List;
   publicclassAndroidCameraApiextendsAppCompatActivity {
privatestaticfinalStringTAG="AndroidCameraApi";
private Button takePictureButton;
private TextureView textureView;
privatestaticfinalSparseIntArrayORIENTATIONS=newSparseIntArray();
static {
    ORIENTATIONS.append(Surface.ROTATION_0, 90);
    ORIENTATIONS.append(Surface.ROTATION_90, 0);
    ORIENTATIONS.append(Surface.ROTATION_180, 270);
    ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
private String cameraId;
protected CameraDevice cameraDevice;
protected CameraCaptureSession cameraCaptureSessions;
protected CaptureRequest captureRequest;
protected CaptureRequest.Builder captureRequestBuilder;
private Size imageDimension;
private ImageReader imageReader;
private File file;
privatestaticfinalintREQUEST_CAMERA_PERMISSION=200;
privateboolean mFlashSupported;
private Handler mBackgroundHandler;
private HandlerThread mBackgroundThread;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_android_camera_api);
    textureView = (TextureView) findViewById(R.id.texture);
    assert textureView != null;
    textureView.setSurfaceTextureListener(textureListener);
    takePictureButton = (Button) findViewById(R.id.btn_takepicture);
    assert takePictureButton != null;
    takePictureButton.setOnClickListener(newView.OnClickListener() {
        @OverridepublicvoidonClick(View v) {
            takePicture();
        }
    });
}
TextureView.SurfaceTextureListenertextureListener=newTextureView.SurfaceTextureListener() {
    @OverridepublicvoidonSurfaceTextureAvailable(SurfaceTexture surface, int width, 
   int height) {
        //open your camera here
        openCamera();
    }
    @OverridepublicvoidonSurfaceTextureSizeChanged(SurfaceTexture surface, int 
 width, int height) {
        // Transform you image captured size according to the surface width 
  and height
    }
    @OverridepublicbooleanonSurfaceTextureDestroyed(SurfaceTexture surface) {
        returnfalse;
    }
    @OverridepublicvoidonSurfaceTextureUpdated(SurfaceTexture surface) {
    }
 };
 privatefinal CameraDevice.StateCallbackstateCallback=newCameraDevice.StateCallback() {
    @OverridepublicvoidonOpened(CameraDevice camera) {
        //This is called when the camera is open
        Log.e(TAG, "onOpened");
        cameraDevice = camera;
        createCameraPreview();
    }
    @OverridepublicvoidonDisconnected(CameraDevice camera) {
        cameraDevice.close();
    }
    @OverridepublicvoidonError(CameraDevice camera, int error) {
        cameraDevice.close();
        cameraDevice = null;
    }
};
final CameraCaptureSession.CaptureCallbackcaptureCallbackListener=newCameraCaptureSession.CaptureCallback() {
    @OverridepublicvoidonCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
        super.onCaptureCompleted(session, request, result);
        Toast.makeText(AndroidCameraApi.this, "Saved:" + file, Toast.LENGTH_SHORT).show();
        createCameraPreview();
    }
};
protectedvoidstartBackgroundThread() {
    mBackgroundThread = newHandlerThread("Camera Background");
    mBackgroundThread.start();
    mBackgroundHandler = newHandler(mBackgroundThread.getLooper());
}
protectedvoidstopBackgroundThread() {
    mBackgroundThread.quitSafely();
    try {
        mBackgroundThread.join();
        mBackgroundThread = null;
        mBackgroundHandler = null;
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
protectedvoidtakePicture() {
    if(null == cameraDevice) {
        Log.e(TAG, "cameraDevice is null");
        return;
    }
    CameraManagermanager= (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    try {
        CameraCharacteristicscharacteristics= manager.getCameraCharacteristics(cameraDevice.getId());
        Size[] jpegSizes = null;
        if (characteristics != null) {
            jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG);
        }
        intwidth=640;
        intheight=480;
        if (jpegSizes != null && 0 < jpegSizes.length) {
            width = jpegSizes[0].getWidth();
            height = jpegSizes[0].getHeight();
        }
        ImageReaderreader= ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
        List<Surface> outputSurfaces = newArrayList<Surface>(2);
        outputSurfaces.add(reader.getSurface());
        outputSurfaces.add(newSurface(textureView.getSurfaceTexture()));
        final CaptureRequest.BuildercaptureBuilder= cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
        captureBuilder.addTarget(reader.getSurface());
        captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
        // Orientationintrotation= getWindowManager().getDefaultDisplay().getRotation();
        captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
        finalFilefile=newFile(Environment.getExternalStorageDirectory()+"/pic.jpg");
        ImageReader.OnImageAvailableListenerreaderListener=newImageReader.OnImageAvailableListener() {
            @OverridepublicvoidonImageAvailable(ImageReader reader) {
                Imageimage=null;
                try {
                    image = reader.acquireLatestImage();
                    ByteBufferbuffer= image.getPlanes()[0].getBuffer();
                    byte[] bytes = newbyte[buffer.capacity()];
                    buffer.get(bytes);
                    save(bytes);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (image != null) {
                        image.close();
                    }
                }
            }
            privatevoidsave(byte[] bytes)throws IOException {
                OutputStreamoutput=null;
                try {
                    output = newFileOutputStream(file);
                    output.write(bytes);
                } finally {
                    if (null != output) {
                        output.close();
                    }
                }
            }
        };
        reader.setOnImageAvailableListener(readerListener, mBackgroundHandler);
        final CameraCaptureSession.CaptureCallbackcaptureListener=newCameraCaptureSession.CaptureCallback() {
            @OverridepublicvoidonCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
                super.onCaptureCompleted(session, request, result);
                Toast.makeText(AndroidCameraApi.this, "Saved:" + file, Toast.LENGTH_SHORT).show();
                createCameraPreview();
            }
        };
        cameraDevice.createCaptureSession(outputSurfaces, newCameraCaptureSession.StateCallback() {
            @OverridepublicvoidonConfigured(CameraCaptureSession session) {
                try {
                    session.capture(captureBuilder.build(), captureListener, mBackgroundHandler);
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }
            @OverridepublicvoidonConfigureFailed(CameraCaptureSession session) {
            }
        }, mBackgroundHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}
protectedvoidcreateCameraPreview() {
    try {
        SurfaceTexturetexture= textureView.getSurfaceTexture();
        assert texture != null;
        texture.setDefaultBufferSize(imageDimension.getWidth(), imageDimension.getHeight());
        Surfacesurface=newSurface(texture);
        captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        captureRequestBuilder.addTarget(surface);
        cameraDevice.createCaptureSession(Arrays.asList(surface), newCameraCaptureSession.StateCallback(){
                    @OverridepublicvoidonConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                        //The camera is already closedif (null == cameraDevice) {
                            return;
                        }
                        // When the session is ready, we start displaying the preview.
                        cameraCaptureSessions = cameraCaptureSession;
                        updatePreview();
                    }
                    @OverridepublicvoidonConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
                        Toast.makeText(AndroidCameraApi.this, "Configuration change", Toast.LENGTH_SHORT).show();
                    }
                }, null);
        } catch (CameraAccessException e) {
             e.printStackTrace();
        }
}
privatevoidopenCamera() {
    CameraManagermanager= (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    Log.e(TAG, "is camera open");
    try {
        cameraId = manager.getCameraIdList()[0];
        CameraCharacteristicscharacteristics= manager.getCameraCharacteristics(cameraId);
        StreamConfigurationMapmap= characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        assert map != null;
        imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
        // Add permission for camera and let user grant the permissionif (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(AndroidCameraApi.this, newString[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
            return;
        }
        manager.openCamera(cameraId, stateCallback, null);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
    Log.e(TAG, "openCamera X");
}
protectedvoidupdatePreview() {
    if(null == cameraDevice) {
        Log.e(TAG, "updatePreview error, return");
    }
    captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
    try {
        cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}
privatevoidcloseCamera() {
    if (null != cameraDevice) {
        cameraDevice.close();
        cameraDevice = null;
    }
    if (null != imageReader) {
        imageReader.close();
        imageReader = null;
    }
}
@OverridepublicvoidonRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNullint[] grantResults) {
    if (requestCode == REQUEST_CAMERA_PERMISSION) {
       if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
            // close the app
            Toast.makeText(AndroidCameraApi.this, "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show();
            finish();
       }
    }
}
@OverrideprotectedvoidonResume() {
    super.onResume();
    Log.e(TAG, "onResume");
    startBackgroundThread();
    if (textureView.isAvailable()) {
        openCamera();
    } else {
        textureView.setSurfaceTextureListener(textureListener);
    }
}
@OverrideprotectedvoidonPause() {
    Log.e(TAG, "onPause");
    //closeCamera();
    stopBackgroundThread();
    super.onPause();
}
 }

try this code it helps you.

Post a Comment for "Why Camera2 Api Working Not Correct?"