在new runOnUiThread

时间:2016-04-21 11:34:11

标签: android android-camera surfaceview

抱歉我的英文。我有activity1activity2。在activity1我有按钮,当我点击此按钮时,此按钮会冻结几秒钟,此后会打开activity2。要在activity1中单击按钮时删除冻结,我添加了在新runOnUiThread中启动相机但现在未调用surfaceCreated的代码。

mPreview - 我的自定义surfaceView

mCamera - 对象相机

我的代码:

new Thread(new Runnable() {
    @Override
    public void run() {
        CameraActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mPreview.addCamera(mCamera);
                mPreview.addParent(CameraActivity.this);
                mCamera.getParameters().setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
                mPreview.refreshDrawableState();
                mCamera.startPreview();
            }
        });
    }
}).start();

我的服务SurfaceView(我只添加重要代码)

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    public CameraPreview (Context context){
        super(context);
    }
    public CameraPreview(Context context, AttributeSet attrs){
        super(context, attrs);
    }
    public CameraPreview(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void addCamera(Camera camera){
            mCamera = camera;
            mHolder = getHolder();
            mHolder.addCallback(this);
            mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {

            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();

        } catch (IOException e) {
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        try {
            if(mCamera!=null){
                mCamera.stopPreview();
                mCamera.setPreviewCallback(null);

                mCamera.release();
                mCamera = null;
            }
        } catch (Exception e){
                Toast.makeText(this.getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    //code
    mCamera.startPreview();
    }
}

1 个答案:

答案 0 :(得分:1)

这是预期的行为,SurfaceSurfaceView维护,作为一种解决方法,您可以检查表面是否有效且具有非0维,并调用surfaceCreated/surfaceChanged函数手动

您需要的代码:

Surface surface = mHolder.getSurface();
if(surface != null && surface.isValid()){
    Rect frame = mHolder.getSurfaceFrame();
    if(frame.width() > 0 && frame.height() > 0){
         surfaceCreated(mHolder);
         surfaceChaged(mHolder, PixelFormat.OPAQUE, frame.width(), frame.height()); //pixel format OPAQUE is the default one
    }
}