1

在调试器中运行它,我看到 info.facing == 0。这意味着它是一个后置摄像头。

当我尝试实例化 Camrea 对象时,我得到空值。

在模拟器上,我将设备设置为禁用后置摄像头并启用前置摄像头。为什么设备认为没有背面摄像头?

我正在使用 Eclipse ADT。

这是我的方法。我从来没有到达第二个循环。getCamreaInstance 正在返回为空的 c。

public static Camera getCameraInstance(){
        Camera c = null;

        CameraInfo info = new CameraInfo();
        if (info.facing == CameraInfo.CAMERA_FACING_BACK){

            //Calling Camera.open() throws an exception if the camera is already in use by another application, so we wrap it in a try block.
            //Failing to check for exceptions if the camera is in use or does not exist will cause your application to be shut down by the system.
            try {
                c = Camera.open();
            }
            catch (Exception e){
                // Camera is not available (in use or does not exist)
            }
            return c;
        }
        //we want the back facing, if we cant get that then we try and get the front facing
        else if (info.facing == CameraInfo.CAMERA_FACING_FRONT){
            c = Camera.open(Camera.getNumberOfCameras()-1); //i should test and see if -1 is a valid value in the case that a device has no camera
            return c;
        }
        else{
            //there are no cameras, so we need to account for that since 'c' will be null
            return c;
        }

    }
4

1 回答 1

1

This line:

CameraInfo info = new CameraInfo();

does not get the current camera configuration. It's just an empty default constructor. The only way to get an accurate CameraInfo object is Camera#getCameraInfo().

The reason you're getting a null Camera is because the default facing is 0. So, it enters the first block, tries to open() which returns null because:

If the device does not have a back-facing camera, this returns null.

You can just call getNumberOfCameras() from the start to see how many cameras there are. Then open one and check it's CameraInfo to see which way it's facing.

However, if you always want the back-facing camera by default(which seems likely, given your code), just remove the checks to facing and check for null on open().

于 2013-10-02T15:31:16.680 回答