带有线程的两个SurfaceView - 相机预览无法恢复

时间:2013-10-23 16:58:34

标签: android multithreading camera surfaceview

我正在创建一个应用程序,可在相机预览之上显示动态图像。我这样做的方法是在我的主要活动中的framelayout中添加两个SurfaceView,一个拿着相机预览,一个拿着我的动画。所以基本上有三个公共类,一个内部线程类在运动图片类中来控制动画。

启动应用程序时工作正常 - 相机正在预览,图片正在移动。但是然后如果我暂停活动,通过进入主屏幕或通过点击图片重定向到另一个活动,然后恢复,相机预览就会变黑。如果我旋转手机那么奇怪的部分就是进入一个不同的模式(风景/肖像),事情恢复正常。

我读过几篇关于相机没有恢复的文章,但解决方案都是关于打开相机。我非常确定我的问题与检查后的相机实例无关。实际上,如果我通过进入主屏幕暂停活动,当我恢复时,相机会出现一秒钟然后变黑。

我一直在尝试各种各样的事情,包括在OnPause()中删除布局中的所有视图,并在添加视图时指定索引号。但是,当我在下面的块中注释掉画布锁时,唯一有点进步的方法。如果没有锁定,图片会随机移动,但相机可以恢复。事实上,如果我省略了关于线程的所有事情并且只显示静态图片,那么相机也可以正常工作。所以我觉得我的帖子出了问题,但我想不出来。

这是线程的运行方法:

    public void run() {
        Canvas canvas;
        while (isRunning) {         //When setRunning(false) occurs, isRunning is 
            canvas = null;          //set to false and loop ends, stopping thread
            try {
                canvas = surfaceHolder.lockCanvas(null);        //Lock
                        synchronized (surfaceHolder) {
                                //Insert methods to modify positions of items in onDraw()
                                animation();
                                postInvalidate();
                            }
            } finally {
                if (canvas != null) {
                    surfaceHolder.unlockCanvasAndPost(canvas);  //Unlock
                            }
                    }
        }
    }

这是开始线程的部分:

    public void surfaceCreated(SurfaceHolder arg0) {
        setWillNotDraw(false); //Allows us to use invalidate() to call onDraw()

        thread = new BubbleThread(getHolder(), this);   //Start the thread that
        thread.setRunning(true);                        //will make calls to 
        thread.start();                                 //onDraw()
    }

这是完成主题的部分:

    public void surfaceDestroyed(SurfaceHolder arg0) {
        try {
            thread.setRunning(false);                //Tells thread to stop
        thread.join();                              //Removes thread from mem.
        } catch (InterruptedException e) {}
    }

[更新]主要活动代码:

    public class MainActivity extends Activity {
    ... // Declarations

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            /* Adjust app settings */
            ...

            //Load();
        }

        public void Load(){
            /* Try to get the camera */
            Camera c = getCameraInstance();

            /* If the camera was received, create the app */
            if (c != null){
                // Create the parent layout to layer the
                // camera preview and bubble layer
                parentLayout = new FrameLayout(this);
                parentLayout.setLayoutParams(new LayoutParams(
                    LayoutParams.MATCH_PARENT,
                    LayoutParams.MATCH_PARENT));

                // Create a new camera view and add it to the layout
                cameraPreview = new CameraPreview(this, c);
                parentLayout.addView(cameraPreview, 0);

                // Create a new draw view and add it to the layout
                bubbleLayer = new BubbleLayer(this);
                parentLayout.addView(bubbleLayer, 1);

                // Set the layout as the apps content view 
                setContentView(parentLayout);
            }
            /* If the camera was not received, close the app */
            else {
                Toast toast = Toast.makeText(getApplicationContext(), 
                    "Unable to find camera. Closing.", Toast.LENGTH_SHORT);
                    toast.show();
                finish();
            }
        }

        /** A safe way to get an instance of the Camera object. */
        /** This method is strait from the Android API */
        public static Camera getCameraInstance(){
            Camera c = null;
            try {
                // Attempt to get a Camera instance
                c = Camera.open();
            }
            catch (Exception e){
                // Camera is not available (in use or does not exist)
                e.printStackTrace();
            }
            return c;
        }

        /* Override the onPause method so that we 
        * can release the camera when the app is closing.
        */
        @Override
        protected void onPause() {
            super.onPause();
            if (cameraPreview != null){
                cameraPreview.onPause();
                cameraPreview = null;
            }
        }

        /* We call Load in our Resume method, because 
        * the app will close if we call it in onCreate
        */
        @Override 
        protected void onResume(){
            super.onResume();
            Load();
        }
    }

[/ UPDATE]

[UPDATE2]相机预览代码:

    public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
        ... // Declarations
        public CameraPreview(Context context, Camera camera) {
            super(context);
            this.context = context;
            mCamera = camera;
            // Install a SurfaceHolder.Callback so we get notified when the
            // underlying surface is created and destroyed.
            mHolder = getHolder();
            mHolder.addCallback(this);
            // deprecated setting, but required on Android versions prior to 3.0
            mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) {
            if (mHolder.getSurface() == null){
                // preview surface does not exist
                return;
            }

            Camera.Parameters parameters = mCamera.getParameters();
            Size bestSize = getBestSize(parameters.getSupportedPreviewSizes(),
                    width,height);
            parameters.setPreviewSize(bestSize.width, bestSize.height);
            mCamera.setParameters(parameters);
            // stop preview before making changes
            try {
                mCamera.stopPreview();
            } catch (Exception e){
                // ignore: tried to stop a non-existent preview
            }
            // set preview size and make any resize, rotate or
            // reformatting changes here
            // start preview with new settings
            try {
                mCamera.setPreviewDisplay(mHolder);
                setCameraDisplayOrientation();
                mCamera.startPreview();
            } catch (Exception e){
                Log.d("CameraView", "Error starting camera preview: "
                    + e.getMessage());
            }
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            // The Surface has been created, now tell the
            // camera where to draw the preview.
            try {
                mCamera.setPreviewDisplay(holder);
                mCamera.startPreview();
            } catch (IOException e) {
                Log.d("CameraView", "Error setting camera preview: "
                    + e.getMessage());
            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            // empty. Take care of releasing the Camera preview in your activity.
        }

        /* Find the best size for camera */
        private Size getBestSize(List<Size> sizes, int w, int h) {
            final double ASPECT_TOLERANCE = 0.05;
            double targetRatio = (double) w / h;
            if (sizes == null) return null;

            Size bestSize = null;
            double minDiff = Double.MAX_VALUE;

            int targetHeight = h;

            // Try to find an size match aspect ratio and size
            for (Size size : sizes) {
                double ratio = (double) size.width / size.height;
                if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    bestSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }

            // Cannot find the one match the aspect ratio, ignore the requirement
            if (bestSize == null) {
                minDiff = Double.MAX_VALUE;
                for (Size size : sizes) {
                    if (Math.abs(size.height - targetHeight) < minDiff) {
                        bestSize = size;
                        minDiff = Math.abs(size.height - targetHeight);
                    }
                }
            }
            return bestSize;
        }


        private void setCameraDisplayOrientation() {        
            if (mCamera == null) return;

            Camera.CameraInfo info = new Camera.CameraInfo();
            Camera.getCameraInfo(0, info);
            WindowManager winManager = (WindowManager)
                        context.getSystemService(Context.WINDOW_SERVICE);
        int rotation = winManager.getDefaultDisplay().getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0: degrees = 0; break;
            case Surface.ROTATION_90: degrees = 90; break;
            case Surface.ROTATION_180: degrees = 180; break;
            case Surface.ROTATION_270: degrees = 270; break;
        }

        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        }
        else {  // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }
        mCamera.setDisplayOrientation(result);
        }

    public void onPause() {
        if (mCamera == null) return;
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }    
    }

[/ UPDATE2]

我发现的另一件事是,当我暂停活动时,解锁很少被执行。虽然当它被执行时摄像头仍然没有回来,但是这种行为对我来说似乎很奇怪,因为执行了thread.join()所以我认为finally块也应该已经执行了。

抱歉,我不能用较少的话语来表达我的问题,但请留下任何线索。提前谢谢!

1 个答案:

答案 0 :(得分:3)

我仍然不确切知道我的程序出了什么问题。但是在研究之后,我发现SurfaceView的z顺序似乎并不遵循正常的规则。因此,我没有使用两个SurfaceViews,一个用于相机,一个用于绘图,我切换到使用一个SurfaceView,现在它工作正常。

但是根据我的实验,无论是哪种实现,在屏幕上绘制相机预览都是一个缓慢的实现,因为线程之间的所有切换。所以人们应该尽量避免在设计中这样做......