1. Get the actual resolution of the camera preview.
=> To make a Preview work, you need to set a SurfaceProvider. When using PreviewView, usually you will create the SurfaceProvider via PreviewView#createSurfaceProvider(). To obtain the requested surface resolution for Preview, you will need to implement your own SurfaceProvider. Then, you can receive the SurfaceRequest object and get the requested resolution via SurfaceRequest#getResolution(). If you don't want to implement the whole SurfaceProvider, you may just need to wrap the original SurfaceProvider provided by PreviewView#createSurfaceProvider(). Please refer to the following sample code. I have done some tests and it should work.
Preview preview = new Preview.Builder()
.setTargetName("Preview")
.build();
Preview.SurfaceProvider surfaceProvider = mPreviewView.createSurfaceProvider();
preview.setSurfaceProvider(surfaceRequest -> {
// Obtain Preview requested surface here via surfaceRequest.getResolution().
surfaceProvider.onSurfaceRequested(surfaceRequest);
});
2. Is the only way to set the target resolution by listening to device orientation, and swapping the width and height
=> Yes, it is the only way to specify the conditions for your target resolution. If you have some specific requirements to request a target resolution, the target rotation is needed such that CameraX can correctly find the suitable resolution. Otherwise, it may cause a FOV double-crop problem. For example, if your app have a landscape 16:9 preview design on a portrait phone device and only a 16:9 target resolution is specified, finally CameraX will select 1920x1080 without considering the target rotation. But most device's max sensor active buffer array is 4:3. The 1920x1080 output has been cropped from the full 4:3 sensor active buffer array. When the app transforms the 1920x1080 frame buffer to the landscape 16:9 preview on a portrait phone device, a second time crop occurs if the display scale type is FILL_CENTER.
Current auto-resolution mechanism will try to select the sizes as large as possible for Preview and ImageCapture. For ImageAnalysis, the size closest to 640x480 between 640x480 and 1920x1080 will be selected. If you do not have a specific size range requirement but only have aspect ratio requirement, you can consider to use setTargetApectRatio() instead. The target rotation setting is unnecessary for the setTargetApectRatio() API.