我遵循了这些教程:
https://developer.android.com/training/camerax/preview,
https://proandroiddev.com/update-android-camerax-4a44c3e4cdcc
第一次运行应用程序时,预览有效,但是旋转屏幕后一切都坏了。我重新安装了应用程序,但是预览不再起作用
public class ScanActivity extends AppCompatActivity {
private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
private PreviewView cameraView;
private Preview imagePreview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
cameraView = findViewById(R.id.cameraView);
cameraProviderFuture = ProcessCameraProvider.getInstance(this);
if(isPermissionsGranted()){
cameraView.post(new Runnable() {
@Override
public void run() {
startCamera();
}
});
}
else{
ActivityCompat.requestPermissions(ScanActivity.this,
new String[]{Manifest.permission.CAMERA},PERMISSION_REQUEST_CODE);
}
}
private void startCamera(){
imagePreview = new Preview.Builder()
.setTargetRotation(cameraView.getDisplay().getRotation())
.build();
imagePreview.setSurfaceProvider(cameraView.getPreviewSurfaceProvider());
final CameraSelector cameraSelector = new CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build();
cameraProviderFuture.addListener(() -> {
try {
ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
cameraProvider.bindToLifecycle(ScanActivity.this,cameraSelector,imagePreview);
} catch (ExecutionException|InterruptedException e) {
e.printStackTrace();
}
},ContextCompat.getMainExecutor(this));
}
}
最佳答案
在初始化相机之前,不应构建用例,这是ProcessCameraProvider.getInstance()
异步进行的操作。因此,您可能会遇到在初始化完成之前就构建了Preview用例的情况,这就是为什么预览无法正常工作的原因。您的代码应该看起来像这样。
cameraProviderFuture.addListener(() -> {
try {
ProcessCameraProvider cameraProvider = cameraProviderFuture.get(context);
Preview preview = new Preview.Builder().build();
preview.setSurfaceProvider(previewView.getSurfaceProvider());
cameraProvider.bindToLifecycle(lifecycleOwner, selector, preview);
} catch (Exception exception) {
exception.printStackTrace();
}
}, ContextCompat.getMainExecutor(context));
关于java - CameraX PreviewView什么也没显示,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60978235/