androidandroid-6.0-marshmallowandroid-camera2android-textureview

Camera2: SurfaceTexture buffer size is being overridden


I am writing an app using Camera2 API, which should show preview from camera and take a picture. Currently my code works as follows:

  1. When Camera Fragment is instantiated, wait for TextureView.SurfaceTextureListener.onSurfaceTextureAvailable to be called
  2. In ViewModel get available and suitable picture and preview sizes from CameraCharacteristics, and emit found preview size to Fragment with LiveData
  3. Fragment observes preview size LiveData and calls setDefaultBufferSize with new size for its TextureView's SurfaceTexture
  4. When new size is set, capture session is created, and repeating preview request is set, so TextureView starts to show image from camera
  5. To avoid disrupting other camera apps' work, all camera-related things are cleared after Fragment's onPause and steps 1-4 are followed again after onResume
  6. Surface instance is shared between Fragment and camera logic classes: the shared variable is initialized with it in TextureView.SurfaceTextureListener.onSurfaceTextureAvailable and is set to null when TextureView.SurfaceTextureListener.onSurfaceTextureDestroyed is called

This works fine for some devices of popular brands with modern Android versions, but the app should work on the particular generic Chinese tablet with Android 6 ("CameraManager: Using legacy camera HAL"), and there I face a problem.


Solution

  • Solved this by overriding onSurfaceTextureSizeChanged of SurfaceTextureListener and calling surfaceTexture.setDefaultBufferSize there with the desired preview size. When default buffer size is overridden with incorrect size (during initialization), this method is called, and I override it again.