To perform basic camera actions like capturing a photo or video using the device's default camera application, you do not need to integrate with aCamera library.Instead, use anIntent
.
Take a photo with a camera app
Android delegates actions to other applications by invoking anIntent
.This process involves three pieces: theIntent
itself, a call to start the externalActivity
,and some code to handle the image data when focus returns to your activity.
Here's a function that invokes anIntent
to capture a photo.
Kotlin
valREQUEST_IMAGE_CAPTURE=1 privatefundispatchTakePictureIntent(){ valtakePictureIntent=Intent(MediaStore.ACTION_IMAGE_CAPTURE) try{ startActivityForResult(takePictureIntent,REQUEST_IMAGE_CAPTURE) }catch(e:ActivityNotFoundException){ // display error state to the user } }
Java
staticfinalintREQUEST_IMAGE_CAPTURE=1; privatevoiddispatchTakePictureIntent(){ IntenttakePictureIntent=newIntent(MediaStore.ACTION_IMAGE_CAPTURE); try{ startActivityForResult(takePictureIntent,REQUEST_IMAGE_CAPTURE); }catch(ActivityNotFoundExceptione){ // display error state to the user } }
Record a video with a camera app
You can also invoke anIntent
to capture a video.
Kotlin
valREQUEST_VIDEO_CAPTURE=1 privatefundispatchTakeVideoIntent(){ Intent(MediaStore.ACTION_VIDEO_CAPTURE).also{takeVideoIntent-> takeVideoIntent.resolveActivity(packageManager)?.also{ startActivityForResult(takeVideoIntent,REQUEST_VIDEO_CAPTURE) }?:run{ //display error state to the user } } }
Java
staticfinalintREQUEST_VIDEO_CAPTURE=1; privatevoiddispatchTakeVideoIntent(){ IntenttakeVideoIntent=newIntent(MediaStore.ACTION_VIDEO_CAPTURE); if(takeVideoIntent.resolveActivity(getPackageManager())!=null){ startActivityForResult(takeVideoIntent,REQUEST_VIDEO_CAPTURE); } else{ //display error state to the user } }
ThestartActivityForResult()
method is protected by a condition that callsresolveActivity()
,which returns the first activity component that can handle theIntent
.Perform this check to ensure that you are invoking anIntent
that won't crash your app.
Additional Resources
For basic camera actions, use anIntent
.Otherwise, it is recommended to use the Camera2 and CameraX libraries for anything more complex than basic image or video capture.