我使用ViewPager和3个片段进行3标签设置。其中一个片段实现了QR码扫描器(ZBarScanner),它使用设备摄像头的实时视图填充整个片段。
我发现这个摄像头视图会导致用户界面严重滞后。用于在选项卡之间滑动的动画要慢得多,并且应用程序CPU使用率大幅增加。运行跟踪视图显示扫描程序库的“onPreviewFrame”方法占用了大部分处理器时间。
我尝试过使用offscreenPageLimit - 我发现需要将其设置为2以保持相机视图处于活动状态,否则由于反复启动和关闭相机视图而导致滑动时会出现非常大的延迟。
如何减少相机预览在我的应用程序中创建的延迟?
如果有帮助,我可以发布代码,但这一切都相当简单。
答案 0 :(得分:2)
使用 TextureView 显示预览。
它很有用:How can I make my view pager more smooth?
祝你好运!
<强> 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>
祝你好运!