Android:无法将 LifeCycleOwner 转换为 CamerX 预览代码中的 activity 错误

Android: cannot cast LifeCycleOwner to an activity error in CamerX preview code

我正在尝试使用相机 API 在 textureView 上显示相机的预览... 在 java 中几乎没有任何与 cameraX api 有关的教程,所以很难理解 API 的工作原理......代码给了我一个运行时异常,它指出

"Activity cannot be cast to lifeCycleowner"

PreviewConfig config = new PreviewConfig.Builder().build();
Preview preview = new Preview(config);

preview.setOnPreviewOutputUpdateListener(
    new Preview.OnPreviewOutputUpdateListener() {
        @Override
        public void onUpdated(Preview.PreviewOutput previewOutput) {

            textureView.setSurfaceTexture(previewOutput.getSurfaceTexture());

        };
});

CameraX.bindToLifecycle((LifecycleOwner) this, preview);

创建您的自定义生命周期

   //lifecycle for camera
        CustomLifecycle lifecycle=new CustomLifecycle();
        lifecycle.doOnResume();
        lifecycle.doOnStart();
        CameraX.bindToLifecycle(lifecycle, preview,imageCapture);


    public class CustomLifecycle implements LifecycleOwner {

        private LifecycleRegistry mLifecycleRegistry;
         CustomLifecycle() {
            mLifecycleRegistry = new LifecycleRegistry(this);
            mLifecycleRegistry.markState(Lifecycle.State.CREATED);
        }

        void doOnResume() {
            mLifecycleRegistry.markState(Lifecycle.State.RESUMED);
        }

        void doOnStart() {
            mLifecycleRegistry.markState(Lifecycle.State.STARTED);
        }

        @NonNull
        public Lifecycle getLifecycle() {
            return mLifecycleRegistry;
        }
    }

camerax官方codelab中已经提示需要更新appcompat依赖:

If Android Studio complains about "this" being not a LifecycleOwner, try rebuilding the project or updating the appcompat dependency to version 1.1.0 or higher.

检查下方 link: https://codelabs.developers.google.com/codelabs/camerax-getting-started/#5

我发布的代码现在运行良好,但我在 activity 中实施它时犯了错误。它必须在片段中实现:|