I’m using Jetpack Compose and I have a modal bottom sheet where users can click on Take a picture
when the bottom sheet pops up. Then they get to the camera view and after taking a picture, they click OK and the picture will be uploaded to a server. So far so good.
The problem here comes when the user is in the camera view (where they can either click on OK to submit the picture they took or cancel) and they press the hardware back button or the cancel button. In this case, the camera view is dismissed and when they click on Take a picture
again, nothing happens.
The code I have is this:
@Composable
fun AppModalBottomSheet(
onShowBottomSheetChanged: (Boolean) -> Unit,
onPictureTaken: (File, Long) -> Unit,
onError: () -> Unit
) {
var shouldShowCameraView by remember { mutableStateOf(false) }
if (shouldShowCameraView) {
ShowCamera(onPictureTaken, onError)
}
}
@Composable
private fun ShowCamera(
onPictureTaken: (file: File, fileSize: Long) -> Unit,
onError: () -> Unit,
) {
val context = LocalContext.current
val imageFile = remember { createImageFile(context) }
val file = imageFile.getOrElse { onError.invoke() } as? File
val fileUri = file?.let { FileUtils.uri(context, file) }
val cameraLauncher =
rememberLauncherForActivityResult(contract = ActivityResultContracts.TakePicture()) {
if (it) {
fileUri?.let { uri ->
val fileSize = FileUtils.fileSize(context, uri)
onPictureTaken(file, fileSize)
}
}
}
LaunchedEffect(key1 = Unit) {
cameraLauncher.launch(fileUri)
}
}
private fun createImageFile(context: Context): Result<File> {
val timeStamp: String =
SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
val imageFileName = "JPEG_" + timeStamp + "_"
val storageDir: File? = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return runCatching {
File.createTempFile(
imageFileName,
".jpeg",
storageDir
)
}
}
After clicking back when they’re in the camera view, when debugging, I set a breakpoint in the line with if (shouldShowCameraView) {
and I can see shouldShowCameraView$delegate
being true
, but the ShowCamera()
function never gets called.
Is there anything I’m missing here? Thanks in advance!