My goal is to take a picture via a camera app and save it to a directory. Much like this tutorial explains: https://developer.android.com/training/camera/photobasics
However, onActivityResult returns -1 as return code on some devices. The problem is most likely that the camera app cannot write the photo file to the URI I provide but I don't understand why.
Here are my tests results:
- Moto G with Android 7: works fine
- Xiaomi Mi A1 with Android 7.1: fails
- Samsung Galaxy A40 with Android 9: fails
Here's what I do:
Declare provider in the manifest (along with the proper permisions)
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.mypackage.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
Declare a proper file path
<paths>
<external-path name="my_images" path="Android/data/com.mypackage/files/Pictures" />
</paths>
In the activity, launch the camera app with an intent
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
takePictureIntent.resolveActivity(requireContext().packageManager)?.also {
val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.FRANCE).format(Date())
requireContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.let { storageDir ->
File.createTempFile("JPEG_${timeStamp}_", ".jpg", storageDir).also {
fileUri = FileProvider.getUriForFile(requireContext(), "com.mypackage.fileprovider", it)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri)
startActivityForResult(takePictureIntent, TAKE_PIC_CODE)
}
}
}
}