Android W/CameraBase: 连接到相机时发生错误:0 on camera.open() 调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26261769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 11:10:37  来源:igfitidea点击:

W/CameraBase﹕ An error occurred while connecting to camera: 0 on camera.open() call

androidandroid-activityandroid-camera

提问by Cjen1

I'm writing a camera app and whenever I call camera.open() the app crashes and then I get this error:

我正在编写一个相机应用程序,每当我调用 camera.open() 应用程序崩溃,然后我得到这个错误:

W/CameraBase﹕ An error occurred while connecting to camera: 0

W/CameraBase﹕ An error occurred while connecting to camera: 0

Here is how I'm opening the camera:

这是我打开相机的方式:

public void getCameraInstance(){
    mCamera = null;

    try 
    {
        mCamera = Camera.open(); // attempt to get a Camera instance
    }

    catch (Exception e)
    {
        // Camera is not available (in use or does not exist)

    }
}

UPDATE:

更新:

If you are reading this please note that this is for the original camera API and no longer applies the the latest version of the camera api (camera2).

如果您正在阅读本文,请注意这是针对原始相机 API 的,不再适用于最新版本的相机 API (camera2)。

You should use the camera2 api from this point onwards as it has greater functionality and also has a better image processing pipeline.

从现在开始,您应该使用 camera2 api,因为它具有更强大的功能并且还具有更好的图像处理管道。

NOTE ONLY VALID UP TO excluding API 21 (Lolipop) i.e. does not apply for Lolipop and above.

注意仅适用于不包括 API 21 (Lolipop),即不适用于 Lolipop 及以上。

采纳答案by madhu131313

To use the following method

要使用以下方法

android.hardware.Camera.open(int cameraId)

You should pass cameraId, If you want the front camera Id you can use the following method

您应该传递cameraId,如果您想要前置摄像头ID,可以使用以下方法

private int findFrontFacingCamera() {

    // Search for the front facing camera
    int numberOfCameras = Camera.getNumberOfCameras();
    for (int i = 0; i < numberOfCameras; i++) {
        CameraInfo info = new CameraInfo();
        Camera.getCameraInfo(i, info);
        if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
            cameraId = i;
            cameraFront = true;
            break;
        }
    }
    return cameraId;
}
  1. If the same camera is opened by other applications, this will throw a RuntimeException.

  2. You must call release() when you are done using the camera, otherwise it will remain locked and be unavailable to other applications.

  3. Your application should only have one Camera object active at a time for a particular hardware camera.

  1. 如果其他应用程序打开了同一个相机,这将抛出一个 RuntimeException。

  2. 使用完相机后必须调用 release() ,否则它将保持锁定状态,其他应用程序无法使用。

  3. 对于特定的硬件相机,您的应用程序一次应该只有一个处于活动状态的 Camera 对象。

回答by Yuri Smirnoff

You manualy uploaded your application to phone. That is why camera permission is not approved. You have to open settings->applications (or something like that) and manualy approve this permission.

您手动将应用程序上传到手机。这就是未批准相机许可的原因。您必须打开设置-> 应用程序(或类似的东西)并手动批准此权限。

回答by Timmmm

In Android 6, make sure you request permission for the camera. Camera access is considered one of the 'dangerous permissions'.

在 Android 6 中,请确保您请求对相机的许可。相机访问被认为是“危险权限”之一

回答by mustafa

make sure your app has permission for camera, e.g

确保您的应用程序具有相机权限,例如

<uses-permission android:name="android.permission.CAMERA"/>

in AndroidManifest.xml

在 AndroidManifest.xml 中

回答by vels

i got the answer for this: this is for marshmallow permission issue: add this in your project:

我得到了答案:这是针对棉花糖许可问题的:将其添加到您的项目中:

step 1:

第1步:

 private static final int REQUEST_GET_ACCOUNT = 112;
 private static final int PERMISSION_REQUEST_CODE = 200;

step2:

第2步:

 int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
            if (checkPermission()) {
                Toast.makeText(getApplicationContext(), "Permission already granted", Toast.LENGTH_LONG).show();
            } else {
                requestPermission();
            }
        }

step3:

第三步:

private boolean checkPermission() {
        int result = ContextCompat.checkSelfPermission(getApplicationContext(), GET_ACCOUNTS);
        int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA);
        return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{GET_ACCOUNTS, CAMERA}, REQUEST_GET_ACCOUNT);
        ActivityCompat.requestPermissions(this, new String[]{WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
    }

    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0) {

                    boolean locationAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    boolean cameraAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;

                    if (locationAccepted && cameraAccepted)
                        Toast.makeText(getApplicationContext(), "Permission Granted, Now you can access location data and camera", Toast.LENGTH_LONG).show();
                    else {
                        Toast.makeText(getApplicationContext(), "Permission Denied, You cannot access location data and camera", Toast.LENGTH_LONG).show();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            if (shouldShowRequestPermissionRationale(WRITE_EXTERNAL_STORAGE)) {
                                showMessageOKCancel("You need to allow access to both the permissions",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                                    requestPermissions(new String[]{WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE},
                                                            PERMISSION_REQUEST_CODE);
                                                }
                                            }
                                        });
                                return;
                            }
                        }

                    }
                }

                break;
        }
    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new android.support.v7.app.AlertDialog.Builder(CaptureActivity.this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }

回答by zakaria

try to close the camera after you finish your work in my case i use mScannerView.stopCamera() because i use it to scan code QR.

在我完成工作后尝试关闭相机,我使用 mScannerView.stopCamera() 因为我用它来扫描二维码。

回答by Nurul Akter Towhid

In my case your code work ,after adding this in AndroidManifest.xml

在我的情况下,您的代码在 AndroidManifest.xml 中添加后工作

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