下面列出了怎么用android.hardware.camera2.CameraCaptureSession的API类实例代码及写法,或者点击链接到github查看源代码。
/**
*
* @param cameraCaptureSession Session
* @param callbackHandler the handler on which the listener should be invoked, or
* {@code null} to use the current thread's {@link android.os.Looper
* looper}.
* @param listener Listener receiving callbacks
* @param lockFocus l
*/
public void start(CameraCaptureSession cameraCaptureSession, boolean lockFocus, Handler callbackHandler, FocusListener listener)
{
mCameraCaptureSession = cameraCaptureSession;
// When the session is ready, we start displaying the preview.
try {
Log.i(TAG, "StartFocusing");
mStateMachine = new FocusingStateMachine(cameraCaptureSession, lockFocus, callbackHandler, listener);
mStateMachine.start(mPreviewSurface);
} catch (Exception e) {
if (cameraCaptureSession != null) {
stop();//cameraCaptureSession.stopRepeating();
}
//mPreviewImageReader.setOnImageAvailableListener(null, null);
mPreviewImageReader = null;
e.printStackTrace();
}
}
@Override
public void onSurfacePrepared(CameraCaptureSession session, Surface surface) {
mSessionFuture.setSession(session);
if (mProxy != null) {
mProxy.onSurfacePrepared(session, surface);
}
// Surface prepared doesn't cause a session state change, so don't trigger the
// state change listener
synchronized (mPreparedSurfaces) {
List<Surface> preparedSurfaces = mPreparedSurfaces.get(session);
if (preparedSurfaces == null) {
preparedSurfaces = new ArrayList<Surface>();
}
preparedSurfaces.add(surface);
mPreparedSurfaces.put(session, preparedSurfaces);
mPreparedSurfaces.notifyAll();
}
}
@Override
public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
if(request.getTag() == ("FOCUS_TAG")) {
//The focus trigger is complete!
//Resume repeating request, clear AF trigger.
mAutoFocusCallback.onAutoFocus(true);
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, null);
mPreviewRequestBuilder.setTag("");
mPreviewRequest = mPreviewRequestBuilder.build();
try {
mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback, mBackgroundHandler);
} catch(CameraAccessException ex) {
Log.d(TAG, "AUTO FOCUS FAILURE: "+ex);
}
} else {
process(result);
}
}
@Override
public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
if (request.getTag() == ("FOCUS_TAG")) {
//The focus trigger is complete!
//Resume repeating request, clear AF trigger.
mAutoFocusCallback.onAutoFocus(true);
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, null);
mPreviewRequestBuilder.setTag("");
mPreviewRequest = mPreviewRequestBuilder.build();
try {
mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback, mBackgroundHandler);
} catch (CameraAccessException ex) {
Log.d(TAG, "AUTO FOCUS FAILURE: " + ex);
}
} else {
process(result);
}
}
private void startPreview() {
CameraCaptureSession.CaptureCallback listener = new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
}
};
if (cameraDevice == null) return;
try {
previewSession.setRepeatingRequest(previewBuilder.build(), listener, null);
} catch (java.lang.Exception e) {
e.printStackTrace();
}
}
@Override
public void onCaptureFailed(@NonNull CameraCaptureSession session,
@NonNull CaptureRequest request,
@NonNull CaptureFailure failure) {
super.onCaptureFailed(session, request, failure);
this.session = null;
switch (failure.getReason()) {
case CaptureFailure.REASON_ERROR:
Timber.e("Capture failed: REASON_ERROR");
break;
case CaptureFailure.REASON_FLUSHED:
Timber.e("Capture failed: REASON_FLUSHED");
break;
default:
Timber.e("Capture failed: UNKNOWN");
break;
}
}
private void captureStillPicture() {
MLog.d(TAG, "captureStillPicture");
try {
if (null == mCameraDevice) {
return;
}
// This is the CaptureRequest.Builder that we use to take a picture.
final CaptureRequest.Builder captureBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureBuilder.addTarget(mImageReader.getSurface());
// Use the same AE and AF modes as the preview.
captureBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
// setAutoFlash(captureBuilder);
// Orientation
captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, 0);
CameraCaptureSession.CaptureCallback CaptureCallback = new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
Log.d(TAG, "saved to: "); // + mFile.toString());
unlockFocus();
}
};
mCaptureSession.stopRepeating();
mCaptureSession.capture(captureBuilder.build(), CaptureCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
/**
* Capture a still picture. This method should be called when we get a response in
* {@link #mCaptureCallback} from both {@link #lockFocus()}.
*/
private void captureStillPicture() {
Log.d(TAG, "captureStillPicture: ");
try {
final Activity activity = getActivity();
if (null == activity || null == mCameraDevice) {
return;
}
// This is the CaptureRequest.Builder that we use to take a picture.
final CaptureRequest.Builder captureBuilder =
mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureBuilder.addTarget(mImageReader.getSurface());
// Use the same AE and AF modes as the preview.
captureBuilder.set(CaptureRequest.CONTROL_AF_MODE,
CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
captureBuilder.set(CaptureRequest.CONTROL_AE_MODE,
CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
captureBuilder.set(CaptureRequest.JPEG_ORIENTATION,
getJpegOrientation(mCharacteristics, mOrientation));
CameraCaptureSession.CaptureCallback CaptureCallback
= new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request,
TotalCaptureResult result) {
showToast("Saved Picture");
//unlockFocus();
}
};
mCaptureSession.stopRepeating();
mCaptureSession.capture(captureBuilder.build(), CaptureCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigured(CameraCaptureSession session) {
final long ident = Binder.clearCallingIdentity();
try {
mExecutor.execute(() -> mCallback.onConfigured(session));
} finally {
Binder.restoreCallingIdentity(ident);
}
}
@Override
public void onCaptureQueueEmpty(CameraCaptureSession session) {
final long ident = Binder.clearCallingIdentity();
try {
mExecutor.execute(() -> mCallback.onCaptureQueueEmpty(session));
} finally {
Binder.restoreCallingIdentity(ident);
}
}
@Override
public void onClosed(CameraCaptureSession session) {
final long ident = Binder.clearCallingIdentity();
try {
mExecutor.execute(() -> mCallback.onClosed(session));
} finally {
Binder.restoreCallingIdentity(ident);
}
}
@Override
public void onConfigured(CameraCaptureSession cameraCaptureSession) {
Log.d(TAG, "CrPreviewSessionListener.onConfigured");
mPreviewSession = cameraCaptureSession;
try {
// This line triggers the preview. A |listener| is registered to receive the actual
// capture result details. A CrImageReaderListener will be triggered every time a
// downloaded image is ready. Since |handler| is null, we'll work on the current
// Thread Looper.
mPreviewSession.setRepeatingRequest(
mPreviewRequest, new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureCompleted(CameraCaptureSession session,
CaptureRequest request, TotalCaptureResult result) {
mLastExposureTimeNs =
result.get(CaptureResult.SENSOR_EXPOSURE_TIME);
}
}, null);
} catch (CameraAccessException | SecurityException | IllegalStateException
| IllegalArgumentException ex) {
Log.e(TAG, "setRepeatingRequest: ", ex);
return;
}
// Now wait for trigger on CrPreviewReaderListener.onImageAvailable();
nativeOnStarted(mNativeVideoCaptureDeviceAndroid);
changeCameraStateAndNotify(CameraState.STARTED);
}
@Override
public void onCaptureCompleted(@NonNull CameraCaptureSession session,
@NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
Face[] faces = result.get(CaptureResult.STATISTICS_FACES);
if (faceDetectorCallback != null) {
faceDetectorCallback.onGetFaces(faces);
}
}
private void captureStillPicture() {
try {
if (null == mCameraDevice) {
return;
}
final CaptureRequest.Builder captureBuilder =
mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureBuilder.addTarget(mImageReader.getSurface());
captureBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getPhotoOrientation(cameraConfigProvider.getSensorPosition()));
CameraCaptureSession.CaptureCallback CaptureCallback = new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureCompleted(@NonNull CameraCaptureSession session,
@NonNull CaptureRequest request,
@NonNull TotalCaptureResult result) {
Log.d(TAG, "onCaptureCompleted: ");
}
};
mCaptureSession.stopRepeating();
mCaptureSession.capture(captureBuilder.build(), CaptureCallback, null);
} catch (CameraAccessException e) {
Log.e(TAG, "Error during capturing picture");
}
}
/**
* Captures a still picture.
*/
void captureStillPicture() {
try {
CaptureRequest.Builder captureRequestBuilder = mCamera.createCaptureRequest(
CameraDevice.TEMPLATE_STILL_CAPTURE);
captureRequestBuilder.addTarget(mImageReader.getSurface());
captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
mCaptureRequestBuilder.get(CaptureRequest.CONTROL_AF_MODE));
updateFlashLightState();
// Calculate JPEG orientation.
@SuppressWarnings("ConstantConditions")
int sensorOrientation = mCameraCharacteristics.get(
CameraCharacteristics.SENSOR_ORIENTATION);
captureRequestBuilder.set(CaptureRequest.JPEG_ORIENTATION,
(sensorOrientation +
mDisplayOrientation * (mConfig.getCurrentFacing() == Constants.CAMERA_FACING_FRONT ? 1 : -1) +
360) % 360);
// Stop preview and capture a still picture.
mCaptureSession.stopRepeating();
mCaptureSession.capture(captureRequestBuilder.build(),
new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureCompleted(@NonNull CameraCaptureSession session,
@NonNull CaptureRequest request,
@NonNull TotalCaptureResult result) {
unlockFocus();
}
}, null);
} catch (CameraAccessException e) {
Log.e(TAG, "Cannot capture a still picture.", e);
}
}
@Override
public void createReprocessableCaptureSessionByConfigurations(InputConfiguration inputConfig,
List<OutputConfiguration> outputs,
android.hardware.camera2.CameraCaptureSession.StateCallback callback, Handler handler)
throws CameraAccessException {
if (DEBUG) {
Log.d(TAG, "createReprocessableCaptureSessionWithConfigurations");
}
if (inputConfig == null) {
throw new IllegalArgumentException("inputConfig cannot be null when creating a " +
"reprocessable capture session");
}
if (outputs == null) {
throw new IllegalArgumentException("Output configurations cannot be null when " +
"creating a reprocessable capture session");
}
// OutputConfiguration objects aren't immutable, make a copy before using.
List<OutputConfiguration> currentOutputs = new ArrayList<OutputConfiguration>();
for (OutputConfiguration output : outputs) {
currentOutputs.add(new OutputConfiguration(output));
}
createCaptureSessionInternal(inputConfig, currentOutputs,
callback, checkAndWrapHandler(handler),
/*operatingMode*/ICameraDeviceUser.NORMAL_MODE, /*sessionParams*/ null);
}
@Override
public void onCaptureFailed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureFailure failure) {
if(request.getTag() == "FOCUS_TAG") {
Log.d(TAG, "Manual AF failure: "+failure);
mAutoFocusCallback.onAutoFocus(false);
}
}
@Override
public void createCustomCaptureSession(InputConfiguration inputConfig,
List<OutputConfiguration> outputs,
int operatingMode,
android.hardware.camera2.CameraCaptureSession.StateCallback callback,
Handler handler) throws CameraAccessException {
List<OutputConfiguration> currentOutputs = new ArrayList<OutputConfiguration>();
for (OutputConfiguration output : outputs) {
currentOutputs.add(new OutputConfiguration(output));
}
createCaptureSessionInternal(inputConfig, currentOutputs, callback,
checkAndWrapHandler(handler), operatingMode, /*sessionParams*/ null);
}
@Override
public CaptureRequest.Builder createCaptureRequest(int templateType,
Set<String> physicalCameraIdSet)
throws CameraAccessException {
synchronized(mInterfaceLock) {
checkIfCameraClosedOrInError();
for (String physicalId : physicalCameraIdSet) {
if (physicalId == getId()) {
throw new IllegalStateException("Physical id matches the logical id!");
}
}
CameraMetadataNative templatedRequest = null;
templatedRequest = mRemoteDevice.createDefaultRequest(templateType);
// If app target SDK is older than O, or it's not a still capture template, enableZsl
// must be false in the default request.
if (mAppTargetSdkVersion < Build.VERSION_CODES.O ||
templateType != TEMPLATE_STILL_CAPTURE) {
overrideEnableZsl(templatedRequest, false);
}
CaptureRequest.Builder builder = new CaptureRequest.Builder(
templatedRequest, /*reprocess*/false, CameraCaptureSession.SESSION_ID_NONE,
getId(), physicalCameraIdSet);
return builder;
}
}
@Override
public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
// The camera is already closed
if (mCameraDevice == null) {
return;
}
// When the session is ready, we start capture.
mCaptureSession = cameraCaptureSession;
triggerImageCapture();
}
@SuppressLint("NewApi")
@Override
public void setCaptureRequest(CaptureRequest.Builder requestBuilder, CameraCaptureSession cameraCaptureSession, Handler handler) {
requestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
requestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
try {
cameraCaptureSession.setRepeatingRequest(requestBuilder.build(),null,handler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigured(CameraCaptureSession session) {
CameraPluginActivity.this._captureSession = session;
try {
session.setRepeatingRequest(createCaptureRequest(), null, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void startPreview(CameraCaptureSession session) {
mCameraCaptureSession = session;
mCaptureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
HandlerThread backgroundThread = new HandlerThread("CameraPreview");
backgroundThread.start();
Handler backgroundHandler = new Handler(backgroundThread. getLooper());
try {
mCameraCaptureSession
.setRepeatingRequest(mCaptureRequestBuilder.build(), null, backgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@SuppressLint("NewApi")
@Override
public void setCaptureRequest(CaptureRequest.Builder requestBuilder, CameraCaptureSession cameraCaptureSession, Handler handler) {
requestBuilder.set(CaptureRequest.CONTROL_AE_MODE,CaptureRequest.CONTROL_AE_MODE_OFF);
requestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
try {
cameraCaptureSession.setRepeatingRequest(requestBuilder.build(),null,handler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
/**
* Wait until the designated surface is prepared by the camera capture session.
*
* @param session the input {@link CameraCaptureSession} to wait for
* @param surface the input {@link Surface} to wait for
* @param timeoutMs how many milliseconds to wait for
*
* @throws TimeoutRuntimeException if waiting for more than {@long timeoutMs}
*/
public void waitForSurfacePrepared(
CameraCaptureSession session, Surface surface, long timeoutMs) {
synchronized (mPreparedSurfaces) {
List<Surface> preparedSurfaces = mPreparedSurfaces.get(session);
if (preparedSurfaces != null && preparedSurfaces.contains(surface)) {
return;
}
try {
long waitTimeRemaining = timeoutMs;
while (waitTimeRemaining > 0) {
long waitStartTime = SystemClock.elapsedRealtime();
mPreparedSurfaces.wait(timeoutMs);
long waitTime = SystemClock.elapsedRealtime() - waitStartTime;
waitTimeRemaining -= waitTime;
preparedSurfaces = mPreparedSurfaces.get(session);
if (waitTimeRemaining >= 0 && preparedSurfaces != null &&
preparedSurfaces.contains(surface)) {
return;
}
}
throw new TimeoutRuntimeException(
"Unable to get Surface prepared in " + timeoutMs + "ms");
} catch (InterruptedException ie) {
throw new AssertionError();
}
}
}
private void updatePreview(CameraCaptureSession cameraCaptureSession) {
if (null == cameraDevice) {
return;
}
captureSession = cameraCaptureSession;
previewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
previewRequest = previewRequestBuilder.build();
try {
captureSession.setRepeatingRequest(previewRequest, captureCallback, backgroundHandler);
} catch (Exception e) {
Log.e(TAG, "Error updating preview: ", e);
}
setFlashModeAndBuildPreviewRequest(configurationProvider.getFlashMode());
}
@Override
public void onCaptureCompleted(@NonNull CameraCaptureSession session,
@NonNull CaptureRequest request,
@NonNull TotalCaptureResult result) {
session.close();
mCaptureSession = null;
Log.d(TAG, "CaptureSession closed");
}
/**
* Capture a still picture. This method should be called when we get a response in
* {@link #mCaptureCallback} from both {@link #lockFocus()}.
*/
private void captureStillPicture() {
try {
if (null == mCameraDevice) {
return;
}
if (mShutterCallback != null) {
mShutterCallback.onShutter();
}
// This is the CaptureRequest.Builder that we use to take a picture.
final CaptureRequest.Builder captureBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureBuilder.addTarget(mImageReaderStill.getSurface());
// Use the same AE and AF modes as the preview.
captureBuilder.set(CaptureRequest.CONTROL_AF_MODE, mFocusMode);
if (mFlashSupported) {
captureBuilder.set(CaptureRequest.CONTROL_AE_MODE, mFlashMode);
}
// Orientation
captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getOrientation(mDisplayOrientation));
CameraCaptureSession.CaptureCallback CaptureCallback = new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
unlockFocus();
}
};
mCaptureSession.stopRepeating();
mCaptureSession.capture(captureBuilder.build(), CaptureCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void captureStillPicture() {
try {
if (null == cameraDevice) {
return;
}
final CaptureRequest.Builder captureBuilder =
cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureBuilder.addTarget(imageReader.getSurface());
captureBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getPhotoOrientation(configurationProvider.getSensorPosition()));
CameraCaptureSession.CaptureCallback CaptureCallback = new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureCompleted(@NonNull CameraCaptureSession session,
@NonNull CaptureRequest request,
@NonNull TotalCaptureResult result) {
Log.d(TAG, "onCaptureCompleted: ");
}
};
captureSession.stopRepeating();
captureSession.capture(captureBuilder.build(), CaptureCallback, null);
} catch (CameraAccessException e) {
Log.e(TAG, "Error during capturing picture");
}
}
@Override
public void onCaptureSequenceCompleted(CameraCaptureSession session, int sequenceId,
long frameNumber)
{
mCallback.onCaptureSequenceCompleted(AndroidCameraCaptureSessionProxy.this,
sequenceId, frameNumber);
}