TakePictureActivityContract
Activity result contract for capturing photos with the camera.
This contract simplifies camera integration by handling the camera intent and returning both the success status and the URI where the photo was saved. Unlike the standard TakePicture contract, this returns the URI in the result.
Setup in Composable
@Composable
fun ProfileScreen(
onPhotoTaken: (Uri) -> Unit
) {
val context = LocalContext.current
val photoUri = remember {
FileProvider.getUriForFile(
context,
"${context.packageName}.fileprovider",
File(context.cacheDir, "photo_${System.currentTimeMillis()}.jpg")
)
}
val takePictureLauncher = rememberLauncherForActivityResult(
contract = TakePictureActivityContract()
) { (success, uri) ->
if (success) {
onPhotoTaken(uri)
}
}
Button(onClick = { takePictureLauncher.launch(photoUri) }) {
Text("Take Photo")
}
}Content copied to clipboard
With Permission Handling
val cameraPermissionLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission()
) { granted ->
if (granted) {
takePictureLauncher.launch(photoUri)
}
}
Button(onClick = {
when (PackageManager.PERMISSION_GRANTED) {
ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) -> {
takePictureLauncher.launch(photoUri)
}
else -> {
cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
}
}
}) {
Text("Take Photo")
}Content copied to clipboard
FileProvider Configuration
Add to AndroidManifest.xml:
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>Content copied to clipboard
Create res/xml/file_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<cache-path name="camera_photos" path="/" />
</paths>Content copied to clipboard
Result Handling
The contract returns Pair<Boolean, Uri>:
first:trueif photo was captured,falseif user cancelledsecond: URI where the photo was saved (same as input URI)
See also
Functions
Link copied to clipboard
Creates an intent to launch the camera for capturing a photo.
Link copied to clipboard
open override fun getSynchronousResult(context: Context, input: Uri): ActivityResultContract.SynchronousResult<Pair<Boolean, Uri>>?
Returns null as this contract requires launching an activity.
Link copied to clipboard