Android相机应用程序在onResume()之后冻结黑屏

时间:2014-08-25 15:49:01

标签: android android-camera surfaceview onresume onpause

我正在开发一个类似于camscanner的应用程序。在我的应用程序中,我有一个相机api我打电话。首次打开应用程序并按下相机按钮时,它可以工作,但是当我单击主页按钮并再次打开我的应用程序时,它会冻结并显示黑屏而不会导致应用程序崩溃。我发现了类似的问题,但没有一个能给我一个正确的答案,我知道我可能不得不改变onResume或onPause中的某些内容,并需要帮助来弄清楚是什么。

下面我有我的CameraScreen活动:

公共类CameraScreen扩展了Activity {

ImageView image;
Activity context;
Preview preview;
Camera camera;
Button exitButton;
ImageView fotoButton;
LinearLayout progressLayout;
String path = "/sdcard/KutCamera/cache/images/";
FrameLayout frame;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.camera_layout);

    context=this;

    fotoButton = (ImageView) findViewById(R.id.imageView_foto);
    exitButton = (Button) findViewById(R.id.button_exit);
    image = (ImageView) findViewById(R.id.imageView_photo);
    progressLayout = (LinearLayout) findViewById(R.id.progress_layout);

    preview = new Preview(this,
            (SurfaceView) findViewById(R.id.KutCameraFragment));
    frame = (FrameLayout) findViewById(R.id.preview);
    frame.addView(preview);
    preview.setKeepScreenOn(true);
    fotoButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            try {
                takeFocusedPicture();
            } catch (Exception e) {

            }
            exitButton.setClickable(true);
            fotoButton.setClickable(false);
            progressLayout.setVisibility(View.VISIBLE);
        }
    });
}


@Override
protected void onPause() {
    super.onPause();
    //releaseMediaRecorder();       // if you are using MediaRecorder, release it first
    //releaseCamera();  
    if(null != camera){
        camera.release();
        camera = null;
    }
    frame.removeView(preview);
    preview = null;// release the camera immediately on pause event
}



private void releaseCamera(){

    if (camera != null){
        camera.release();        // release the camera for other applications
        camera = null;
    }
}


@Override
protected void onResume() {
    super.onResume();
    // TODO Auto-generated method stub
    if(camera==null){

        Log.d("Camera tes", "Camera==null");
        //camera.setPreviewCallback(null);
    camera = Camera.open();
    camera.startPreview();

    camera.setErrorCallback(new ErrorCallback() {
        public void onError(int error, Camera mcamera) {

            camera.release();
            camera = Camera.open();
            Log.d("Camera died", "error camera");

        }
    });

    }
    if (camera != null) {
        //camera.setPreviewCallback(null);
        Log.d("Camera tes", "Camera!=null");
        if (Build.VERSION.SDK_INT >= 14)
            setCameraDisplayOrientation(context,
                    CameraInfo.CAMERA_FACING_BACK, camera);
        preview.setCamera(camera);
    }

}


private void setCameraDisplayOrientation(Activity activity, int cameraId,
        android.hardware.Camera camera) {
    android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
    android.hardware.Camera.getCameraInfo(cameraId, info);
    int rotation = activity.getWindowManager().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;
    }
    camera.setDisplayOrientation(result);
}



Camera.AutoFocusCallback mAutoFocusCallback = new Camera.AutoFocusCallback() {
    @Override
    public void onAutoFocus(boolean success, Camera camera) {

        try{
        camera.takePicture(mShutterCallback, null, jpegCallback);
        }catch(Exception e){

        }

    }
};

Camera.ShutterCallback mShutterCallback = new ShutterCallback() {

    @Override
    public void onShutter() {
        // TODO Auto-generated method stub

    }
};
public void takeFocusedPicture() {
    camera.autoFocus(mAutoFocusCallback);

}

PictureCallback rawCallback = new PictureCallback() {
    public void onPictureTaken(byte[] data, Camera camera) {
        // Log.d(TAG, "onPictureTaken - raw");
    }
};

PictureCallback jpegCallback = new PictureCallback() {
    @SuppressWarnings("deprecation")
    public void onPictureTaken(byte[] data, Camera camera) {

        FileOutputStream outStream = null;
        Calendar c = Calendar.getInstance();
        File videoDirectory = new File(path);

        if (!videoDirectory.exists()) {
            videoDirectory.mkdirs();
        }

        try {
            // Write to SD Card
            outStream = new FileOutputStream(path + c.getTime().getSeconds() + ".jpg");
            outStream.write(data);
            outStream.close();


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }


        Bitmap realImage;
         final BitmapFactory.Options options = new BitmapFactory.Options();
          options.inSampleSize = 5;

            options.inPurgeable=true;                   //Tell to gc that whether it needs free memory, the Bitmap can be cleared

            options.inInputShareable=true;              //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future


        realImage = BitmapFactory.decodeByteArray(data,0,data.length,options);
        ExifInterface exif = null;
        try {
            exif = new ExifInterface(path + c.getTime().getSeconds()
                    + ".jpg");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            Log.d("EXIF value",
                    exif.getAttribute(ExifInterface.TAG_ORIENTATION));
            if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
                    .equalsIgnoreCase("1")) {
                realImage = rotate(realImage, 90);
            } else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
                    .equalsIgnoreCase("8")) {
                realImage = rotate(realImage, 90);
            } else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
                    .equalsIgnoreCase("3")) {
                realImage = rotate(realImage, 90);
            } else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
                    .equalsIgnoreCase("0")) {
                realImage = rotate(realImage, 90);
            }
        } catch (Exception e) {

        }

        image.setImageBitmap(realImage);



        fotoButton.setClickable(true);
        camera.startPreview();
        progressLayout.setVisibility(View.GONE);
        exitButton.setClickable(true);

    }
};

public static Bitmap rotate(Bitmap source, float angle) {
    Matrix matrix = new Matrix();
    matrix.postRotate(angle);
    return Bitmap.createBitmap(source, 0, 0, source.getWidth(),
            source.getHeight(), matrix, false);
}

}

这里我有我的预览课程:

类预览扩展ViewGroup实现SurfaceHolder.Callback {     private final String TAG =“预览”;

SurfaceView mSurfaceView;
SurfaceHolder mHolder;
int heightmax ;
int widthmax ;
Size mPreviewSize;
List<Size> mSupportedPreviewSizes;
Camera mCamera;

@SuppressWarnings("deprecation")
Preview(Context context, SurfaceView sv) {
    super(context);

    mSurfaceView = sv;
//        addView(mSurfaceView);

    mHolder = mSurfaceView.getHolder();
    mHolder.addCallback(this);
    mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

public void setCamera(Camera camera) {
    mCamera = camera;
    if (mCamera != null) {
        mSupportedPreviewSizes = mCamera.getParameters().getSupportedPictureSizes();
        requestLayout();

        // get Camera parameters
        Camera.Parameters params = mCamera.getParameters();

        List<String> focusModes = params.getSupportedFocusModes();
        if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
            // set the focus mode
            params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
            // set Camera parameters
            mCamera.setParameters(params);
        }

    }
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    // We purposely disregard child measurements because act as a
    // wrapper to a SurfaceView that centers the camera preview instead
    // of stretching it.
    final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
    final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
    setMeasuredDimension(width, height);

    if (mSupportedPreviewSizes != null) {

      mPreviewSize=maxSize();

    }
}

public Size maxSize(){


    Size sizeMax=mSupportedPreviewSizes.get(0);

    maxsize=mSupportedPreviewSizes.get(0)
                 .height*mSupportedPreviewSizes.get(0).width;

    for(Size size:mSupportedPreviewSizes){
        if(size.height*size.width>sizeMax.width*sizeMax.height){
            sizeMax = size;

        }
    }

    return sizeMax;


}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    if (changed && getChildCount() > 0) {
        final View child = getChildAt(0);

        final int width = r - l;
        final int height = b - t;

        int previewWidth = width;
        int previewHeight = height;
        if (mPreviewSize != null) {
            previewWidth = mPreviewSize.width;
            previewHeight = mPreviewSize.height;
        }

        // Center the child SurfaceView within the parent.
        if (width * previewHeight > height * previewWidth) {
            final int scaledChildWidth = previewWidth * height / previewHeight;
            child.layout((width - scaledChildWidth) / 2, 0,
                    (width + scaledChildWidth) / 2, height);
        } else {
            final int scaledChildHeight = previewHeight * width / previewWidth;
            child.layout(0, (height - scaledChildHeight) / 2,
                    width, (height + scaledChildHeight) / 2);
        }
    }
}

public void surfaceCreated(SurfaceHolder holder) {
    // The Surface has been created, acquire the camera and tell it where
    // to draw.
    try {
        if (mCamera != null) {
            mCamera.setPreviewDisplay(holder);
        }
    } catch (IOException exception) {
        Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
    }
}

public void surfaceDestroyed(SurfaceHolder holder) {
    // Surface will be destroyed when we return, so stop the preview.
    /*
    mCamera.stopPreview();
    mCamera.setPreviewCallback(null);
    mCamera.release();
    mCamera = null;

    if (mCamera != null) {
        mCamera.stopPreview();

    }
   */
}




Camera.AutoFocusCallback mnAutoFocusCallback = new Camera.AutoFocusCallback() {
    @Override
    public void onAutoFocus(boolean success, Camera camera) {



    }
};
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    /*
    if(mCamera != null) {
        Camera.Parameters parameters = mCamera.getParameters();
        parameters.setPictureSize(mPreviewSize.width, mPreviewSize.height);
        requestLayout();

        mCamera.setParameters(parameters);
        mCamera.startPreview();

    }
    */
}

}

我会劝告你能给我的任何帮助或指南。

0 个答案:

没有答案
相关问题