I\'m looking for a way to correctly share (not OPEN) an internal file with external application using Android Support library\'s FileProvider.
Following the example
This solution works for me since OS 4.4. To make it work on all devices I added a workaround for older devices. This ensures that always the safest solution is used.
Manifest.xml:
file_paths.xml:
Java:
public static void sendFile(Context context) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
String dirpath = context.getFilesDir() + File.separator + "directory";
File file = new File(dirpath + File.separator + "file.txt");
Uri uri = FileProvider.getUriForFile(context, "com.package.name.fileprovider", file);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// Workaround for Android bug.
// grantUriPermission also needed for KITKAT,
// see https://code.google.com/p/android/issues/detail?id=76683
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
List resInfoList = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
context.grantUriPermission(packageName, attachmentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
if (intent.resolveActivity(context.getPackageManager()) != null) {
context.startActivity(intent);
}
}
public static void revokeFileReadPermission(Context context) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
String dirpath = context.getFilesDir() + File.separator + "directory";
File file = new File(dirpath + File.separator + "file.txt");
Uri uri = FileProvider.getUriForFile(context, "com.package.name.fileprovider", file);
context.revokeUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
The permission is revoked with revokeFileReadPermission() in the onResume and onDestroy() methods of the Fragment or the Activity.