我有一个使用 ViewPager 和 3 个 fragment 的 3 选项卡设置。其中一个 fragment 实现了二维码扫描器 (ZBarScanner),它使用设备摄像头的实时 View 填充整个 fragment 。
我发现此相机 View 会导致用户界面严重滞后。在选项卡之间滑动的动画要慢得多,应用程序的 CPU 使用率也大幅增加。运行跟踪 View 显示扫描程序库的“onPreviewFrame”方法占用了大部分处理器时间。
我试过使用 offscreenPageLimit - 我发现需要将其设置为 2 以保持相机 View 有效,否则由于反复启动和关闭相机 View ,滑动时会出现非常严重的延迟。
如何减少相机预览在我的应用程序中造成的延迟?
如果有帮助,我可以发布代码,但这一切都相当简单。
最佳答案
我花了很多时间和咖啡,但找到了麻烦的原因。 使用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>
祝你好运!
关于android - 当 fragment 包含相机预览时 ViewPager 滑动滞后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28183017/