Skip to content

Instantly share code, notes, and snippets.

@EduardoSP6
Last active August 13, 2019 14:20
Show Gist options
  • Save EduardoSP6/ed84108a1bad2ea72526a398b1ea457a to your computer and use it in GitHub Desktop.
Save EduardoSP6/ed84108a1bad2ea72526a398b1ea457a to your computer and use it in GitHub Desktop.
Grant external access to files in android (FileUriExposedException)
1- Create Android resource directory (XML type) in res folder;
2- Create new xml file inside de directory called (provider_paths.xml), with content:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="external_files"
path="." />
</paths>
3- Create provider tag on AndroidManifest.xml inside the application tag:
<application
android:name=".MainApplication"
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:replace="android:allowBackup">
<!-- Provide to grant access to files for share -->
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
...
</application>
4- Now you can open, edit and share files throught Intent.
Sharing image example:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri fileURI = FileProvider.getUriForFile(
getContext(),
getContext().getApplicationContext()
.getPackageName() + ".provider", file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(fileURI, "image/*");
intent.putExtra(Intent.EXTRA_STREAM, fileURI);
startActivity(intent);
} else {
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
startActivity(Intent.createChooser(intent, "Compartilhar imagem via"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment