简体   繁体   中英

Camera error: Cannot connect to the camera

I want to use the built-in camera functionality of a device. having read the documentation, this is the method I am using

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }
}

In the manifest I added the usage:

<uses-feature android:name="android.hardware.camera"
              android:required="true" />

However, when I invoke the method, the error dialog appears. Why is that?

Using camera with ACTION_IMAGE_CAPTURE intent with target API 23 or higher requires camera permission. You must request this permission at runtime.

Here you can find a video tutorial on this topic.

If you want to open the camera on button click, use the code below.

Initialize the button and image view within the onCreate() method.

photoButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
            startActivityForResult(cameraIntent, CAMERA_REQUEST); 
        }
    });
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {  
        Bitmap photo = (Bitmap) data.getExtras().get("data"); 
        if(photo!=null)
            imageView.setImageBitmap(photo);
    }  
} 

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