How to open a file in another app with FileProvider for Android 7+
Android 7 Nougat and higher have new security restrictions which makes Uri.parse() unusable to get access to files in internal or external storage. Instead, we need to use the FileProvider class which is available in the Android Support Library. In this tutorial, I show you how to use FileProvider to access files in internal and external storage.
How to open a file in another app with FileProvider
- If you do not include the Android Support Library in your build.gradle yet, then you need to so so we can use FileProvider.
- Create a paths.xml in your xml folder. If you do not have this folder, you can create it with Android Studio. Here, you specify to which file paths your FileProvider should grant you access.
- Specify the default FileProvider or create your own CustomFileProvider which inherits from FileProvider in AndroidManifest.xml.
- Do not forget to declare your needed permission in AndroidManifest.xml! If you want to open a file (e.g. a video), you need the permission to access the external storage. Otherwise, the file access may fail silently.
- Use the default FileProvider or your CustomFileProvider to get your files.
AndroidManifest.xml: we specify our provider. Make sure to set exported to false and grantUriPermissions to true! If you want to create a custom FileProvider (a class which extends FileProvider), then you need to change the name of the provider.
<!-- Needed for Android >= Nougat for file access -->
provider_paths.xml: depending on which storage you need to access, you need to use something else than external-path. See the documentation for other options.
<external-path name="external_files" path="."/>
YourActivitity.java: in this example, I want to open a file in a video player app. We either use the default FileProvider or our custom FileProvider we created earlier. For context, you can use this if you are inside an activity. Make sure to call grantUriPermission and add the appropriate flag to your Intent.
final Uri data = FileProvider.getUriForFile(context, "myprovider", new File(file_path));
context.grantUriPermission(context.getPackageName(), data, Intent.FLAG_GRANT_READ_URI_PERMISSION);
final Intent intent = new Intent(Intent.ACTION_VIEW)
Thank you for reading this tutorial about opening a file in another app using FileProvider. As you can see, the process is fairly easy once you have completed the FileProvider setup. Let me know in the comments if this tutorial helped you.