在Android中使用前置摄像头的麻烦

时间:2013-04-23 18:03:46

标签: android android-camera

我尝试在我的应用程序中实现前置摄像头。我使用了以下代码。它与后置摄像头配合使用。但我不能将相机更换为前置摄像头。

package com.fsp.googleimagesearch;

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

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

public class PixtantCamera extends Activity {

    private Camera mCamera;
    private CameraPreview mCameraPreview;
    Button btn_capture, btn_front_cam;
    FrameLayout preview;
    private SurfaceHolder mSurfaceHolder;

    @Override
    protected void onStop() {
        super.onStop();

        if (mCamera != null) {

            // mCamera.stopPreview();
            stopCamera();
            mCamera.release();
        }
    }

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

        if (mCamera != null) {

            // mCamera.stopPreview();
            stopCamera();
            mCamera.release();
        }
    }

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

        mCamera = getCameraInstance();
        mCameraPreview = new CameraPreview(this, mCamera);
        preview = (FrameLayout) findViewById(R.id.camera_preview);
        preview.addView(mCameraPreview);
        btn_front_cam = (Button) findViewById(R.id.btn_front_cam);

        btn_capture = (Button) findViewById(R.id.btn_click_cam);
        btn_capture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCamera.takePicture(null, null, mPicture);
            }
        });

        btn_front_cam.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (Camera.getNumberOfCameras() >= 2) {
                    // if you want to open front facing camera use this line
                    mCamera = Camera.open(CameraInfo.CAMERA_FACING_FRONT);              
                try {
                    mCameraPreview = new CameraPreview(PixtantCamera.this,
                            mCamera);
                    preview.addView(mCameraPreview);
                }
                catch (Exception e) {
                    mCamera.release();
                }
                mCamera.takePicture(null, null, mPicture);
            }
            }
        });

    }

    public int getFrontCameraId() {
        CameraInfo ci = new CameraInfo();
        for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
            Camera.getCameraInfo(i, ci);
            if (ci.facing == CameraInfo.CAMERA_FACING_FRONT)
                return i;
        }
        return -1; // No front-facing camera found
    }



    private Camera getCameraInstance() {
        Camera camera = null;
        try {
            camera = Camera.open();
        } catch (Exception e) {
            // cannot get camera or does not exist
        }
        return camera;
    }

    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(data);
                fos.close();
            } catch (FileNotFoundException e) {

            } catch (IOException e) {
            }
        }
    };

    private static File getOutputMediaFile() {
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "MyCameraApp");
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());
        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");

        return mediaFile;
    }

    public void stopCamera() {
        // mSurfaceHolder = getHolder();
        mSurfaceHolder.removeCallback(mCameraPreview);
        // mCamera.stopPreview();
    }

    public class CameraPreview extends SurfaceView implements
            SurfaceHolder.Callback {

        // private Camera mCamera;

        // Constructor that obtains context and camera
        @SuppressWarnings("deprecation")
        public CameraPreview(Context context, Camera camera) {
            super(context);
            mCamera = camera;
            mSurfaceHolder = this.getHolder();
            mSurfaceHolder.addCallback(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();
        }

        @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
            }
        }
    }

}

我收到以下错误。

04-23 23:27:34.260: E/AndroidRuntime(24320): FATAL EXCEPTION: main
04-23 23:27:34.260: E/AndroidRuntime(24320): java.lang.RuntimeException: Fail to connect to camera service
04-23 23:27:34.260: E/AndroidRuntime(24320):    at android.hardware.Camera.native_setup(Native Method)
04-23 23:27:34.260: E/AndroidRuntime(24320):    at android.hardware.Camera.<init>(Camera.java:353)
04-23 23:27:34.260: E/AndroidRuntime(24320):    at android.hardware.Camera.open(Camera.java:312)
04-23 23:27:34.260: E/AndroidRuntime(24320):    at com.fsp.googleimagesearch.PixtantCamera$3.onClick(PixtantCamera.java:88)
04-23 23:27:34.260: E/AndroidRuntime(24320):    at android.view.View.performClick(View.java:4262)
04-23 23:27:34.260: E/AndroidRuntime(24320):    at android.view.View$PerformClick.run(View.java:17351)
04-23 23:27:34.260: E/AndroidRuntime(24320):    at android.os.Handler.handleCallback(Handler.java:615)
04-23 23:27:34.260: E/AndroidRuntime(24320):    at android.os.Handler.dispatchMessage(Handler.java:92)
04-23 23:27:34.260: E/AndroidRuntime(24320):    at android.os.Looper.loop(Looper.java:137)
04-23 23:27:34.260: E/AndroidRuntime(24320):    at android.app.ActivityThread.main(ActivityThread.java:4935)
04-23 23:27:34.260: E/AndroidRuntime(24320):    at java.lang.reflect.Method.invokeNative(Native Method)
04-23 23:27:34.260: E/AndroidRuntime(24320):    at java.lang.reflect.Method.invoke(Method.java:511)
04-23 23:27:34.260: E/AndroidRuntime(24320):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
04-23 23:27:34.260: E/AndroidRuntime(24320):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
04-23 23:27:34.260: E/AndroidRuntime(24320):    at dalvik.system.NativeStart.main(Native Method)

我也添加了权限..

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-permission android:name="android.permission.CAMERA" />

1 个答案:

答案 0 :(得分:0)

我认为问题在于,在发布应用当前持有的相机之前,您无法再次拨打Camera.open()。尝试添加mCamera.release()作为onClick btn_front_cam方法的第一行。

编辑:您可能还需要

<uses-feature android:name="android.hardware.camera.autofocus"/> 

以及

<uses-feature android:name="android.hardware.camera.front"/> 

在AndroidManifest.xml文件中。