This is an update for my previous blog post on how to use the camera and photo gallery to get images. Since then, Android made some updates on how the file system works in version 7.0 so the previous approach will not work. I’ll be going over how to fix this issue for Android.
First thing we need to do is to add a FileProvider to the AndroidManifest.xml file. Inside your application tag, add the provider and update the android:authorities value to include your own package name before .fileprovider.
You’ll notice a resource is getting referenced android:resource=”@xml/file_paths”, we need to create this file. In the Android project, create a new folder in the Resources folder called xml. Inside the newly created xml folder, create a new file called file_paths.xml. The contents of the file should look like this:
Again, make sure to update the com.yourcompany.appname to reflect what’s in your Manifest file.
You can find more information on this here.
Launching the camera and photo gallery
If you followed the previous blog, we are going to replace the two methods BringUpCamera() and BringUpPhotoGallery() with the following code. This new approach should work on newer Android OS and the older ones.
Handling the image result
After the picture has been taken with the camera or the image was selected from the gallery, the method OnActivityResult in your MainActivity.cs will get fired as usual. The way I have it set up, if the request code is 0 then we are expecting image data from the camera and if it’s a 1 then it came from the photo gallery; in my situation I wanted to save that image to the Documents Directory for later use. The variable App.selectedImageId is a static string defined in the Forms project, and this value represents the file name for the photo just taken, App.selectedImageId should be the same value as the parameter imageId in the method BringUpCamera(string imageId, FileFormatEnum fileType).
There is a lot going on here but it’s pretty straight forward. Once we get an image, it gets rotated to the orientation it was taken in, saved to the disk if a file name was supplied (only for images taken from the camera) and then using the MessagingCenter to send the bitmap data back up to your UI in the Forms project.