Question

The following code takes a picture with the camera and works fine. When I pause the application (by going back to the home menu) and restart the app, the camera image does not get saved anymore. Even though I release and re-open the camera on pause/resume, I get the error when calling snapPicture: "Method called after release()".

This is my code, and the line 'Log.w("Error message: ", e.getLocalizedMessage());' displays the error. Can anyone help me to solve this problem?

camerapreview.java

package com.example.testproject;

import java.io.IOException;
import android.content.Context;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class CameraPreview extends SurfaceView implements
        SurfaceHolder.Callback {
    private SurfaceHolder mSurfaceHolder;
    private Camera mCamera;

    // Constructor that obtains context and camera
    @SuppressWarnings("deprecation")
    public CameraPreview(Context context, Camera camera) {
        super(context);
        this.mCamera = camera;
        this.mSurfaceHolder = this.getHolder();
        this.mSurfaceHolder.addCallback(this);
        this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        try {
            mCamera.setPreviewDisplay(surfaceHolder);
            mCamera.startPreview();
        } catch (IOException e) {
            // left blank for now
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        mCamera.stopPreview();
        mCamera.release();
        mCamera = null; 
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
            int width, int height) {
        // start preview with new settings
        try {
            mCamera.setPreviewDisplay(surfaceHolder);
            mCamera.startPreview();
        } catch (Exception e) {
            // intentionally left blank for a test
        }
    }
}

custom_cameraactivity.java

package com.example.testproject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

public class Custom_CameraActivity extends Activity {
    private Camera mCamera;
    private CameraPreview mCameraPreview;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public void setCameraAndCameraPreview(Camera mcamera,
            CameraPreview mCameraPreview) {
        this.mCamera = mcamera;
        this.mCameraPreview = mCameraPreview;
    }

    public String snapPicture() {
        TakePictureTaskAsync takePictureTask = new TakePictureTaskAsync();
        takePictureTask.setCamera(mCamera);
        Calendar cal = Calendar.getInstance();
        String useThisTimeStamp = new SimpleDateFormat("HHmmss").format(cal
                .getTime());
        takePictureTask.configureTimestamp(useThisTimeStamp);
        takePictureTask.execute();
        return useThisTimeStamp;
    }

    /**
     * Helper method to access the camera returns null if it cannot get the
     * camera or does not exist
     * 
     * @return
     */

}

class TakePictureTaskAsync extends AsyncTask<Void, Void, Void> {

    private Camera mCamera;
    private String myTimeStamp;

    public void setCamera(Camera mCamera) {
        this.mCamera = mCamera;
    }

    public void configureTimestamp(String timeStamp) {
        this.myTimeStamp = timeStamp;
    }

    @Override
    protected void onPostExecute(Void result) {

    }

    @Override
    protected Void doInBackground(Void... params) {
        try {
            mCamera.takePicture(null, null, mPicture);
        } catch (Exception e) {
            Log.w("Error message: ", e.getLocalizedMessage());
            //this is where the error "method called after release" comes in
            }
        return null;
    }

    PictureCallback mPicture = new PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {

            File pictureFile = getOutputMediaFile();

            if (pictureFile == null) {
                return;
            }
            try {
                FileOutputStream fos = new FileOutputStream(pictureFile);
                fos.write(resizeImage(data));
                fos.close();
            } catch (FileNotFoundException e) {

            } catch (IOException e) {
            }

            try {
                HTTPPost postPictureToURL = new HTTPPost();
                postPictureToURL.setTimestamp(myTimeStamp);
                postPictureToURL.executeImagePOST();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private File getOutputMediaFile() {
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "testdir");
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {

                return null;
            }
        }

        File mediaFile;

        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "cameraView_" + myTimeStamp + ".jpg");

        return mediaFile;
    }

    byte[] resizeImage(byte[] input) {
        Bitmap original = BitmapFactory.decodeByteArray(input, 0, input.length);
        Bitmap resized = Bitmap.createScaledBitmap(original, 800, 600, true);

        ByteArrayOutputStream blob = new ByteArrayOutputStream();
        resized.compress(Bitmap.CompressFormat.JPEG, 70, blob);

        return blob.toByteArray();
    }
}

Mainactivity.java

@Override
protected void onPause() {
    super.onPause();
    try {
        mCamera.stopPreview();
        mCamera.setPreviewCallback(null);
        mCameraPreview.getHolder().removeCallback(mCameraPreview);
        mCamera.release();
        mCamera = null;
    } catch (Exception e) {
        e.printStackTrace();
    }
}

protected void onResume() {
    super.onResume();
    if (mCamera != null) {
        mCamera.startPreview();     
    } else {
        mCamera = getCameraInstance();
        mCamera.startPreview();
    }
}

private Camera getCameraInstance() {
    Camera camera = null;
    try {
        camera = Camera.open();
    } catch (Exception e) {
        //do nothing
    }
    return camera;
}

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top