android.hardware.camera2.CameraAccessException: CAMERA_DISCONNECTED (2): 相机设备已断开连接
创始人
2024-08-20 02:00:11
0

在处理相机相关操作时,可能会遇到“android.hardware.camera2.CameraAccessException: CAMERA_DISCONNECTED (2): 相机设备已断开连接”异常。这个异常表示相机设备在操作时已经断开连接。下面是一个示例的解决方法:

import android.Manifest;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.Collections;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "CameraExample";
    private static final int REQUEST_CAMERA_PERMISSION = 200;

    private SurfaceView surfaceView;
    private CameraManager cameraManager;
    private String cameraId;
    private CameraDevice cameraDevice;
    private CameraCaptureSession cameraCaptureSession;

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

        surfaceView = findViewById(R.id.surfaceView);
        cameraManager = (CameraManager) getSystemService(CAMERA_SERVICE);

        // 检查相机权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
        } else {
            openCamera();
        }

        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
                // 创建 Surface 后,重新打开相机
                if (cameraDevice != null) {
                    closeCamera();
                }
                openCamera();
            }

            @Override
            public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {
                // Surface 发生变化时,重新配置相机
                configureCamera();
            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
                // 销毁 Surface 时,关闭相机
                closeCamera();
            }
        });
    }

    private void openCamera() {
        try {
            cameraId = cameraManager.getCameraIdList()[0];
            cameraManager.openCamera(cameraId, new CameraDevice.StateCallback() {
                @Override
                public void onOpened(@NonNull CameraDevice cameraDevice) {
                    MainActivity.this.cameraDevice = cameraDevice;
                    configureCamera();
                }

                @Override
                public void onDisconnected(@NonNull CameraDevice cameraDevice) {
                    cameraDevice.close();
                    MainActivity.this.cameraDevice = null;
                }

                @Override
                public void onError(@NonNull CameraDevice cameraDevice, int i) {
                    cameraDevice.close();
                    MainActivity.this.cameraDevice = null;
                }
            }, null);
        } catch (CameraAccessException e) {
            Log.e(TAG, "相机访问异常: " + e.getMessage());
        }
    }

    private void closeCamera() {
        if (cameraCaptureSession != null) {
            cameraCaptureSession.close();
            cameraCaptureSession = null;
        }

        if (cameraDevice != null) {
            cameraDevice.close();
            cameraDevice = null;
        }
    }

    private void configureCamera() {
        if (cameraDevice == null) {
            return;
        }

        try {
            Surface surface = surfaceView.getHolder().getSurface();
            cameraDevice.createCaptureSession(Collections.singletonList(surface), new CameraCaptureSession.StateCallback() {
                @Override
                public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                    MainActivity.this.cameraCaptureSession = cameraCaptureSession;
                }

                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
                    Log.e(TAG, "相机配置失败");
                }
            }, null);
        } catch (CameraAccessException e) {
            Log.e(TAG, "相机访问异常: " + e.getMessage());
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openCamera();
            } else {
                Log.e(TAG, "相机权限被拒绝");
            }
        }
    }
}

在上面的示例代码中,我们使用了CameraManager来获取相机设备,并通过cameraManager.openCamera()方法来打开相机。

相关内容

热门资讯

Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
Alertmanager在pr... 首先,在Prometheus配置文件中,确保Alertmanager URL已正确配置。例如:ale...
Aksnginxdomainb... 在AKS集群中,可以使用Nginx代理服务器实现根据域名进行路由。以下是具体步骤:部署Nginx i...
AddSingleton在.N... 在C#中创建Singleton对象通常是通过私有构造函数和静态属性来实现,例如:public cla...
Alertmanager中的基... Alertmanager中可以使用repeat_interval选项指定在一个告警重复发送前必须等待...