我无法使用Camera2获得Android相机图像

时间:2017-07-17 08:13:32

标签: android android-camera2

Android:有什么问题?我正在尝试使用CAMERA2从我的Android相机拍摄照片,但有些东西不起作用。 我只需要从相机中获取视频流并将其显示在屏幕上。代码MainActivity:

public class MainActivity extends AppCompatActivity {
private CameraManager cameraManager = null;
private TextureView textureView = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textureView = (TextureView) findViewById(R.id.textureView);

    cameraManager = (CameraManager) getSystemService(CAMERA_SERVICE);

}

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onResume() {
    super.onResume();
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    try {
        cameraManager.openCamera(cameraManager.getCameraIdList()[0], new CameraDevice.StateCallback() {
            @Override
            public void onOpened(@NonNull CameraDevice camera) {
                CaptureRequest.Builder builder = null;
                try {
                    builder = camera.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
                if(builder != null)
                    if(textureView != null)
                    builder.addTarget(new Surface(textureView.getSurfaceTexture()));
                else onClosed(camera);
            }

            @Override
            public void onDisconnected(@NonNull CameraDevice camera) {
            }

            @Override
            public void onError(@NonNull CameraDevice camera, int error) {

            }
        }, new Handler(getApplicationContext().getMainLooper()));
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

请帮忙

1 个答案:

答案 0 :(得分:0)

请查看camera2的示例视频捕获应用: https://github.com/googlesamples/android-Camera2Video

您当前的代码永远不会使用您的TextureView创建相机捕获会话,您也永远不会向该会话提交重复捕获请求。看看样本,看看它是如何设置相机的。