android – ViewPager在片段包含相机预览时滑动滞后

我有一个使用ViewPager和3个片段的3选项卡设置.其中一个片段实现了QR码扫描器(ZBarScanner),它使用设备摄像头的实时视图填充整个片段.

我发现这个摄像头视图会导致用户界面严重滞后.用于在选项卡之间滑动的动画要慢得多,并且应用程序CPU使用率大幅增加.运行跟踪视图显示扫描程序库的“onPreviewFrame”方法占用了大部分处理器时间.

我尝试过使用offscreenPageLimit – 我发现需要将其设置为2以保持摄像机视图处于活动状态,否则由于反复启动和关闭摄像机视图而导致滑动时会出现非常大的延迟.

我该怎么做才能减少相机预览在我的应用程序中创建的延迟?

我可以发布代码,如果它有帮助,但它都相当简单.

最佳答案 我花了很多时间和咖啡,但找到了麻烦的原因.

使用SurfaceView显示预览的问题.

使用TextureView显示预览.

这将是有用的:How can I make my view pager more smooth?

祝好运!

更新:添加了TextureView的示例

CameraModule.java

public class CameraModule implements SurfaceTextureListener {
    private Camera mCamera;

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
        mCamera = getCamera();

        try {
            mCamera.setPreviewTexture(surface);
            mCamera.startPreview();
        } catch (IOException ioe) {
            // Something bad happened
        }
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
        // Ignored, Camera does all the work for us
    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
        mCamera.stopPreview();
        mCamera.release();
        return true;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) {
        // Invoked every time there's a new Camera preview frame
    }

    private Camera getCamera() {
        Camera cam = null;

        try {
            cam = Camera.open();
        } catch (RuntimeException e) {
            loggerManager.error("Camera not available");
        }

        return cam;
    }
}

CameraFragment.java

public class CameraFragment extends Fragment {

    // You create an instance of the module. I use a singleton.
    CameraModule mCameraModule = new CameraModule();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_camera, container, false);

        TextureView mTextureView = (TextureView) view.findViewById(R.id.camera_preview);
        mTextureView.setSurfaceTextureListener(mCameraModule);

        return view;
    }
}

fragment_camera.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000"
    android:orientation="vertical">

    <TextureView
        android:id="@+id/camera_preview"
        android:layout_width="match_parent"
        android:background="#000"
        android:layout_height="match_parent" />


</RelativeLayout>

祝好运!

点赞