0

enter image description here

When I click the action button to take a picture a pop up dialog appears and tells me "Cant Connect to Camera." Stack trace:

06-06 21:45:26.753: E/ActivityThread(25688): Performing stop of activity that is not resumed: {com.example.dselfies/com.example.dselfies.MainActivity}
06-06 21:45:26.753: E/ActivityThread(25688): java.lang.RuntimeException: Performing stop of activity that is not resumed: {com.example.dselfies/com.example.dselfies.MainActivity}
06-06 21:45:26.753: E/ActivityThread(25688): at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3344)
06-06 21:45:26.753: E/ActivityThread(25688): at android.app.ActivityThread.handleStopActivity(ActivityThread.java:3425)
06-06 21:45:26.753: E/ActivityThread(25688): at android.app.ActivityThread.access$1100(ActivityThread.java:151)
06-06 21:45:26.753: E/ActivityThread(25688): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1332)
06-06 21:45:26.753: E/ActivityThread(25688): at android.os.Handler.dispatchMessage(Handler.java:102)
06-06 21:45:26.753: E/ActivityThread(25688): at android.os.Looper.loop(Looper.java:135)
06-06 21:45:26.753: E/ActivityThread(25688): at android.app.ActivityThread.main(ActivityThread.java:5254)
06-06 21:45:26.753: E/ActivityThread(25688): at java.lang.reflect.Method.invoke(Native Method)
06-06 21:45:26.753: E/ActivityThread(25688): at java.lang.reflect.Method.invoke(Method.java:372)
06-06 21:45:26.753: E/ActivityThread(25688): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
06-06 21:45:26.753: E/ActivityThread(25688): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

https://www.pntbrother.com/fix-cant-connect-to-camera-on-nexus-5-nexus-4-camera-has-stopped-working/

Following the advice linked above I went to developer options and selected "Use AwesomePlayer instead of NuPlayer for most media playback" however the error persists.

When the action button is clicked, onOptionsItemSelected is called and as you can see below dispatchTakePictureIntent is called

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml
   switch (item.getItemId()) {
        case R.id.action_camera:
        dispatchTakePictureIntent();
        // mCamera.takePicture(null, null, mPicture);
         return true;
        case R.id.action_settings:
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

I didn't edit dispatchTakePictureIntent from what was given at the following link: http://developer.android.com/training/camera/photobasics.html

For clarity, here is what I used:

private void dispatchTakePictureIntent() {
    Log.i(TAG,"dispatchTakePictureIntent entered: ");
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            Log.i(TAG,"IOException: " + ex);
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(photoFile));
            Log.i(TAG,"Got here: "+Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
            Log.i(TAG,"Picture successfully saved: "+takePictureIntent);
        }
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.i(TAG,"onActivityResult entered: ");
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");
        mImageView.setImageBitmap(imageBitmap);
    }
}


private File createImageFile() throws IOException {
    // Create an image file name
    Log.i(TAG,"createImageFile entered: ");
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
        imageFileName,  /* prefix */
        ".jpg",         /* suffix */
        storageDir      /* directory */
    );

    if (!storageDir.exists())
        storageDir.mkdirs();

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    Log.i(TAG,"mCurrentPhotoPath: " + mCurrentPhotoPath);
    Log.i(TAG,"image: " + image);
    return image;
}

"Picture successfully saved" (last line in dispatchTakePictureIntent) is displayed by logCat and in the ...Images/Pictures folder of my divice I do indeed find .jpg's that the program generates. However, click on any and they all say "Media not found."

Is this a sure sign that I have to make an asyncTask? I'm having a difficult time making heads or tails of whether this post is relevant. The Handler answer with the delay makes me think I need to make get the activity away from the UIThread, but I'm not sure.

Other very similar posts don't have answers: https://stackoverflow.com/questions/24305700/camera-error-fail-to-connect-to-camera-service Can't connect to camera

My only other hunch is it has something to do with this field that I use for displaying the preview?

private Camera mCamera;

It recieves the following value in surfaceChanged which ultimately does lead to a SurfaceView displaying my beautiful face:

mCamera = Camera.open(0);

So I mean, some sort of connection is made with the Camera.

Here's my code that successfully generates a preview using this Camera object in case you need it:

// Start the preview
private void startPreview() {
    Log.i(TAG,"startPreview entered: " + capture);
    if (null != mCamera) {
        try {
            mCamera.startPreview();
            mIsPreviewing = true;
        } catch (Exception e) {
            Log.e(TAG, "Failed to start preview");
        }
    }
}

// SurfaceHolder callback Object
SurfaceHolder.Callback mSurfaceHolderCallback = new SurfaceHolder.Callback() {
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // Do nothing
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        Log.i(TAG,"surfaceChanged entered: " + capture);
        if (mSurfaceHolder.getSurface() == null) {
            return;
        }

        // Disable touches on mFrame
        //mFrame.setEnabled(false);

        // Shutdown current preview
        //stopPreview();

        if (null == mCamera) {
            try {

                // Returns first back-facing camera or null if no camera is
                // available.
                // May take a long time to complete
                // Consider moving this to an AsyncTask
                mCamera = Camera.open(0);
                Log.e(TAG, "mCamera: "+mCamera);

            } catch (RuntimeException e) {
                Log.e(TAG, "Failed to acquire camera");
            }

            // Ensure presence of camera or finish()
            if (null == mCamera)
                finish();
        }

        setCameraParameters(width, height);

        // Initialize preview display
        try {
            mCamera.setPreviewDisplay(holder);
        } catch (IOException e) {
            Log.e(TAG, "Failed to set preview display in ");
        }

        // Start preview
        try {
            startPreview();
            //mFrame.setEnabled(true);
        } catch (RuntimeException e) {
            Log.e(TAG, "Failed to start preview in surfaceChanged()");
        }
    }

    // Change camera parameters
    private void setCameraParameters(int width, int height) {

        Log.i(TAG,"setCameraParameters entered: " + mCamera);

        // Get camera parameters object
        Camera.Parameters p = mCamera.getParameters();

        Log.i(TAG,"Camera.Parameters p: " + p);

        // Find closest supported preview size
        Camera.Size bestSize = findBestSize(p, width, height);

        // FIX - Should lock in landscape mode?

        int tmpWidth = bestSize.width;
        int tmpHeight = bestSize.height;

        if (bestSize.width < bestSize.height) {
            tmpWidth = bestSize.height;
            tmpHeight = bestSize.width;
        }

        p.setPreviewSize(tmpWidth, tmpHeight);
        mCamera.setParameters(p);
    }

    // Determine the largest supported preview size
    private Camera.Size findBestSize(Camera.Parameters parameters,
            int width, int height) {

        Log.i(TAG,"findBestSize entered: " + capture);

        List<Camera.Size> supportedSizes = parameters
                .getSupportedPreviewSizes();

        Camera.Size bestSize = supportedSizes.remove(0);

        for (Camera.Size size : supportedSizes) {
            if ((size.width * size.height) > (bestSize.width * bestSize.height)) {
                bestSize = size;
            }
        }

        return bestSize;
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // Do Nothing
    }
};

But no Camera object is used anywhere in the code given at this link previously mentioned: http://developer.android.com/training/camera/photobasics.html . Maybe I just don't understand why a Camera object wouldn't be needed to create a connection to the camera when invoking an intent to take a picture.

So...What is going on when I erase the line in onOptionsItemSelected that calls dispatchTakePictureIntent and instead replace it with:

mCamera.takePicture(null, null, mPicture); ?

Because when I do that I get no error message when I click the action button.

Advice?

Community
  • 1
  • 1
Frikster
  • 2,755
  • 5
  • 37
  • 71

1 Answers1

0

I didn't use a camera object when making this project, I simply made the intent with the file URI and dispatched it. If that isn't working

takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);

I suspect you have a problem with your emulator and your physical device. I got the Android Studio emulated camera working immediately with my webcam.

Liquid5n0w
  • 16
  • 2