Android Tutorial Camera2 - Still images and videos

Status
Not open for further replies.
Camera2 library is based on the Camera2 API introduced in Android 5 (API 21).
It is designed to work together with CamEx2 class.
It is supported by B4A v7.3+. The library will be included as an internal library in the next update.

Both image capturing and video recording are supported.
CamEx2 class is built to be extended. Camera2 native API is huge.



The configuration steps:

1. Open the camera when the activity is resumed.
2. Prepare the surface and start preview. The preview size and capture size are set at this point.
3. Stop the camera when the activity is paused.

Take pictures with FocusAndTakePicture or TakePictureNow.

Video capturing is done by calling StartVideoRecording and StopVideoRecording.
The surface needs to be recreated after the video is recorded.

TaskIndex

When you open the camera you receive a number called TaskIndex:
B4X:
Wait For (cam.OpenCamera(front)) Complete (TaskIndex As Int)
If TaskIndex > 0 Then
   MyTaskIndex = TaskIndex 'hold this index. It will be required in later calls.
   Wait For(PrepareSurface) Complete (Success As Boolean)
End If
If the value of TaskIndex is 0 then the camera failed to open. Otherwise you need to store it in a global variable and pass it to other camera methods.

The camera can be stopped or reopened while other asynchronous tasks are running. The task index is used to cancel running tasks in such cases.

Notes & tips

- The RECORD_AUDIO is not added automatically as it is only required when recording video. In such case you need to add it with the manifest editor:
B4X:
AddPermission(android.permission.RECORD_AUDIO)

CamEx2 class is is included in the attached example.
It depends on Camera2 v1.10+.

Change log

- V1.31 - Changes the behavior of PreviewCropRegion to affect the captured image as well (previously it was inconsistent).
- V1.30 - Fixes an issue with video orientation.
- V1.20
  • Example updated and targetSdkVersion is set to 26. Permissions are handled at runtime.
  • Digital zoom feature. Note that it only affects the preview.
  • Fixed typo in getSupportedVideoSizes method.

New example:
  • Based on B4XPages (there are instructions inside if you want to use it in an Activity module).
  • Preview image is not stretched.
  • Captured image is shown with the correct orientation.
 

Attachments

  • CamEx2.zip
    22.4 KB · Views: 837
Last edited:

PhiloSophical

Member
Licensed User
Longtime User
Hit this problem with your example when trying to record video.

The app opens up but crashes after pressing the toggle for video/camera

Moto G5 Phone - Android 7.0 SDK24

Error occurred on line: 135 (CamEx2)
android.hardware.camera2.CameraAccessException: CAMERA_ERROR (3): submitRequestList - configured surface is abandoned.

Any ideas?

Thanks

B4X:
'Starts the preview.
Public Sub StartPreview (MyTaskIndex As Int, VideoRecording As Boolean)
    Dim PreviewBuilder As JavaObject
    If VideoRecording Then
        PreviewBuilder = Camera.CreateVideoRequestBuilder      
    Else
        PreviewBuilder = Camera.CreatePreviewBuilder
    End If
    SetSettingsFromMap(PreviewBuilder, PreviewSettingsMap)
    'line 135 follows
    PreviewRequest = Camera.SetRepeatingRequest(PreviewBuilder)
    If PrintKeys Then PrintAllKeys(PreviewRequest, "Preview Capture Request")
End Sub
 
Last edited:

PhiloSophical

Member
Licensed User
Longtime User
Full Error below:-

Logger connected to: motorola Moto G (5)
--------- beginning of main
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
Start success: true
Error occurred on line: 135 (CamEx2)
android.hardware.camera2.CameraAccessException: CAMERA_ERROR (3): submitRequestList - configured surface is abandoned.
at android.hardware.camera2.CameraManager.throwAsPublicException(CameraManager.java:633)
at android.hardware.camera2.impl.ICameraDeviceUserWrapper.submitRequestList(ICameraDeviceUserWrapper.java:86)
at android.hardware.camera2.impl.CameraDeviceImpl.submitCaptureRequest(CameraDeviceImpl.java:865)
at android.hardware.camera2.impl.CameraDeviceImpl.setRepeatingRequest(CameraDeviceImpl.java:904)
at android.hardware.camera2.impl.CameraCaptureSessionImpl.setRepeatingRequest(CameraCaptureSessionImpl.java:236)
at anywheresoftware.b4a.objects.Camera2.SetRepeatingRequest(Camera2.java:359)
at b4a.example3.camex2._startpreview(camex2.java:196)
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:710)
at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:342)
at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:249)
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:139)
at anywheresoftware.b4a.BA.raiseEvent(BA.java:166)
at anywheresoftware.b4a.shell.DebugResumableSub$RemoteResumableSub.resume(DebugResumableSub.java:19)
at anywheresoftware.b4a.BA.checkAndRunWaitForEvent(BA.java:240)
at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:132)
at anywheresoftware.b4a.BA.raiseEvent(BA.java:166)
at anywheresoftware.b4a.keywords.Common$14.run(Common.java:1733)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: android.os.ServiceSpecificException: submitRequestList - configured surface is abandoned.
at android.hardware.camera2.legacy.LegacyCameraDevice.submitRequestList(LegacyCameraDevice.java:425)
at android.hardware.camera2.legacy.CameraDeviceUserShim.submitRequestList(CameraDeviceUserShim.java:443)
at android.hardware.camera2.impl.ICameraDeviceUserWrapper.submitRequestList(ICameraDeviceUserWrapper.java:84)
... 24 more
 

PhiloSophical

Member
Licensed User
Longtime User
Sadly not - crashes immediately with same error - as you probably suspected!
 
Last edited:

PhiloSophical

Member
Licensed User
Longtime User
I found an app "Camera2 probe" - output below - does this help in any way?

Model:Moto G (5)
Manufacturer:motorola
Build:7.0
SDK:24
SupportLevel:2
SupportLevel HR:Legacy
Manual exposure:0
Auto exposure:1
Auto exposure, always flash:1
Auto exposure, auto flash:1
Auto exposure, auto flash redeye:0
AF Lock:1
Manual focus:1
Auto focus:1
Auto focus macro:1
Auto focus continuous picture:1
Auto focus continuous video:1
Auto focus EDOF:0
Whitebalance off:0
Automatic whitebalance:1
WB: cloudy day:1
WB: day:1
WB: fluorescent:1
WB: incandescent:1
WB: shade:1
WB: twilight:1
WB: warm fluorescent:1
AWB Lock:1
RawCapture:0
 

PhiloSophical

Member
Licensed User
Longtime User
Good news - this seems to have fixed the problem.

The original post #1 in this thread now contains the CamEx2 v1.11 code in the attached zip.

Thanks very much.
 

jimmyF

Active Member
Licensed User
Longtime User
BB KeyOne
Android 7.1.1
I wish I could say exactly what is happening at the time but it appears to be quite random.
 

jimmyF

Active Member
Licensed User
Longtime User
No. Filtered.
 

jimmyF

Active Member
Licensed User
Longtime User
These are new, unfiltered. In Release mode.

It hung on me and had to reboot the device to quit the app and turn off the flash.
 

jimmyF

Active Member
Licensed User
Longtime User
In Debug mode. Unfiltered.

 

jimmyF

Active Member
Licensed User
Longtime User
None of the two modes above were in video mode. Camera only.

This is in Video Mode:
 

rboeck

Well-Known Member
Licensed User
Longtime User
I get a crash after switching from photo mode to video mode, when i try to take the first or a second video.

This is my filtred log:
B4X:
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
Start success: true
Unknown const: 18
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Surface android.hardware.camera2.params.OutputConfiguration.getSurface()' on a null object reference
    at android.hardware.camera2.impl.CameraDeviceImpl$CameraDeviceCallbacks.onCaptureErrorLocked(CameraDeviceImpl.java:1925)
    at android.hardware.camera2.impl.CameraDeviceImpl$CameraDeviceCallbacks.onDeviceError(CameraDeviceImpl.java:1693)
    at android.hardware.camera2.legacy.CameraDeviceUserShim$CameraCallbackThread$CallbackHandler.handleMessage(CameraDeviceUserShim.java:299)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:179)
    at android.os.HandlerThread.run(HandlerThread.java:61)
** Activity (main) Pause, UserClosed = true **
Ignoring event: camera_surfaceready
Ignoring event: camera_previewcapturecomplete

Sometimes i see a short message near the camera icon, with something like "camera not ready", but currently i cannot reproduce it.
Mobile is Axon 7, Android 7.1.1
 
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…