如何检测是否有前置摄像头,是否有如何到达和使用前置摄像头?

时间:2010-10-14 21:25:28

标签: android camera

如何检测是否有前置摄像头以及是否有如何使用前置摄像头?

4 个答案:

答案 0 :(得分:19)

如果您使用的是API级别9(Android 2.3)或更高级别,您可以执行以下操作来计算(第一个)前置摄像头的索引:

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
}

然后您可以使用Camera.open方法的索引,例如:

int index = getFrontCameraId();
if (index == -1) error();
Camera c = Camera.open(index);

获取相关的相机。

答案 1 :(得分:5)

Oak您的代码不支持21以上的sdk所以我添加了这些行以使其可用:)

    int getFrontCameraId(CameraManager cManager) {
    if (Build.VERSION.SDK_INT < 22) {
        Camera.CameraInfo ci = new Camera.CameraInfo();
        for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
            Camera.getCameraInfo(i, ci);
            if (ci.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) return i;
        }
    } else {
        try {
            for ( int j = 0;j<cManager.getCameraIdList().length; j++) {
                String[] cameraId = cManager.getCameraIdList();
                CameraCharacteristics characteristics = cManager.getCameraCharacteristics(cameraId[j]);
                int cOrientation = characteristics.get(CameraCharacteristics.LENS_FACING);
                if (cOrientation == CameraCharacteristics.LENS_FACING_FRONT) 
                    return j;
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    return -1; // No front-facing camera found
}

我更新了Oak的代码,现在也支持新的camera2库。

答案 2 :(得分:1)

  

如何检测是否有前置摄像头以及是否有如何使用前置摄像头?

至少通过Android 2.2,没有API。幸运的是,即将发布的Gingerbread版本将为前置摄像头增加内置支持。遗憾!

答案 3 :(得分:0)

Kalpit,我不知道你是如何设法让代码工作的。我试着编辑你的答案,但需要改变完整的答案。这就是我得到的。

@SuppressLint("NewApi" )
int getFrontCameraId() {
    if (Build.VERSION.SDK_INT < 22) {
        Camera.CameraInfo ci = new Camera.CameraInfo();
        for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
            Camera.getCameraInfo(i, ci);
            if (ci.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) return i;
        }
    } else {
        try {
            CameraManager cManager = (CameraManager) getApplicationContext()
               .getSystemService(Context.CAMERA_SERVICE);
            String[] cameraId = cManager.getCameraIdList();
            for ( int j = 0;j<cameraId.length; j++) {
                CameraCharacteristics characteristics = cManager.getCameraCharacteristics(cameraId[j]);
                int cOrientation = characteristics.get(CameraCharacteristics.LENS_FACING);
                if (cOrientation == CameraCharacteristics.LENS_FACING_FRONT)
                    return Integer.parseInt(cameraId[j]);
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    return -1; // No front-facing camera found
}