简体   繁体   中英

How to get an Android camera image with Camera2

Android: What's the problem? I'm trying to get a picture from my Android camera using CAMERA2, but something's not working. I just need to get a video stream from my camera and display it on the screen. Code 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();
    }
}

Please help

Please take a look at the sample video capture app for camera2: https://github.com/googlesamples/android-Camera2Video

Your current code never creates a camera capture session with your TextureView, and you also never submit a repeating capture request to that session. Take a look at the sample to see how it sets up the camera.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM