在表面视图中使用相机后无法释放相机

时间:2018-08-12 15:45:23

标签: android nullpointerexception android-camera

我已经完成了动作检测应用程序。当我尝试通过onPressBack方法返回到上一个活动并尝试释放摄像机时,在摄像机处于打开状态的活动中,在调用camera.release之后出现使用摄像机的错误。

这是活动中运行另一类运动检测的代码

      surfaceView=(SurfaceView)findViewById(R.id.surfaceView);
        mSurfaceHolder = surfaceView.getHolder();

        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
//        new Hour_service(surfaceView);
//        Intent intent=new Intent(MainActivity.this,Hour_service.class);
//        startService(intent);
        txtStatus = (TextView) findViewById(R.id.txtStatus);
        root =findViewById(R.id.activity_main).getRootView();
        motionDetector = new MotionDetector(this, (SurfaceView) surfaceView);
        motionDetector.setMotionDetectorCallback(new MotionDetectorCallback() {
            @Override
            public void onMotionDetected() {
                Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                v.vibrate(50);
                txtStatus.setText("Motion detected");
                bOutput=MotionDetector.bOutput;

                if (first==0) {
                    first++;
                    startTime = SystemClock.uptimeMillis();
                    customHandler.postDelayed(updateTimerThread, 0);
                }
           /*     if(detection_count==5){

                    Intent intent = new Intent(MainActivity.this, RecorderService.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startService(intent);

                }
                detection_count ++ ;*/
            }

            @Override
            public void onTooDark() {
                txtStatus.setText("Too dark here");
                root.setBackgroundColor(Color.parseColor("#000000"));
            }
        });

    }




    private Runnable updateTimerThread = new Runnable() {
        public void run() {
            updatedTime = SystemClock.uptimeMillis() - startTime;
            int secs = (int) (updatedTime / 1000);
            sec=secs;

            if (secs>=16&&save_count>=3){
                save_count=0;
                first=0;
                // Save Video_a;
                // Stop timer
                customHandler.removeCallbacks(updateTimerThread);
            }else if (secs<16&&save_count<=2){


                SaveImage(bOutput);
                save_count++;
            }

            customHandler.postDelayed(this, 5000);
        }

    };
    @Override
    protected void onResume() {
        super.onResume();

        motionDetector.onResume();

        if (motionDetector.checkCameraHardware()) {
//            txtStatus.setText("Camera found");
        } else {
            //  txtStatus.setText("No camera available");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
          motionDetector.onPause();
    }

    @Override
    public void onBackPressed() {
        motionDetector.setMotionDetectorCallback(null);
        motionDetector.onBackPressed();
    }

这是运动检测器类中的代码

 class MotionDetectorThread extends Thread {
        private AtomicBoolean isRunning = new AtomicBoolean(true);

        public void stopDetection() {
            isRunning.set(false);
        }

        @Override
        public void run() {
            while (isRunning.get()) {
                long now = System.currentTimeMillis();
                if (now - lastCheck > checkInterval) {
                    lastCheck = now;

                    if (nextData.get() != null) {
                        int[] img = ImageProcessing.decodeYUV420SPtoLuma(nextData.get(), nextWidth.get(), nextHeight.get());

                        // check if it is too dark
                        int lumaSum = 0;
                        for (int i : img) {
                            lumaSum += i;
                        }
                        if (lumaSum < minLuma) {
                            if (motionDetectorCallback != null) {
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        motionDetectorCallback.onTooDark();
                                    }
                                });
                            }
                        } else if (detector.detect(img, nextWidth.get(), nextHeight.get())) {
                            // check
                            if (motionDetectorCallback != null ) {
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {

                                            Camera.Parameters params = imgCam.getParameters();
                                            int w = params.getPreviewSize().width;
                                            int h = params.getPreviewSize().height;
                                            int format = params.getPreviewFormat();
                                            YuvImage image = new YuvImage(imgByte, format, w, h, null);

                                            ByteArrayOutputStream out = new ByteArrayOutputStream();
                                            Rect area = new Rect(0, 0, w, h);
                                            image.compressToJpeg(area, 100, out);
                                            Bitmap bm = BitmapFactory.decodeByteArray(out.toByteArray(), 0, out.size());


                                            float degrees = 90;//rotation degree
                                            Matrix matrix = new Matrix();
                                            matrix.setRotate(degrees);
                                            bOutput = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);

//                                        mMediaRecorder.start();
//                                        try {
//                                            Thread.sleep(10 * 1000); // This will recode for 10 seconds, if you don't want then just remove it.
//                                        } catch (Exception e) {
//                                            e.printStackTrace();
//                                        }
//                                        getOutputMediaFile(1);
                                            motionDetectorCallback.onMotionDetected();

                                    }

                                });
                            }
                        }
                    }
                }
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

和我创建的一些方法

 public void onResume() {


        if (checkCameraHardware()) {

            mCamera = getCameraInstance();
            worker = new MotionDetectorThread();
            worker.start();

            // configure preview
            previewHolder = mSurface.getHolder();
            previewHolder.addCallback(surfaceCallback);
            previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
    }

    public boolean checkCameraHardware() {
        if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }

    private Camera getCameraInstance() {
        Camera c = null;

        try {
            if (Camera.getNumberOfCameras() >= 2) {
                //if you want to open front facing camera use this line
                c = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
            } else {
                c = Camera.open();
            }
        } catch (Exception e) {
            // Camera is not available (in use or does not exist)
            //txtStatus.setText("Kamera nicht zur Benutzung freigegeben");
        }
        return c; // returns null if camera is unavailable
    }

    private Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() {

        /**
         * {@inheritDoc}
         */
        @Override
        public void onPreviewFrame(byte[] data, Camera cam) {
            if (data == null) return;
            Camera.Size size = cam.getParameters().getPreviewSize();
            if (size == null) return;

            consume(data, size.width, size.height);

            imgByte = data;
            imgCam = cam;
        }
    };

0 个答案:

没有答案