i have Permission Denial while sharing a video .mp4 file with file provider and Intent.EXTRA_TEXT .
if i remove the line:
shareIntent.putExtra(Intent.EXTRA_TEXT, "#myappHashtag");
everything works. But i need both video file + extra text.
i think the problem is: caption=%23myappHashtag in the share uri but how can i fix it?
Thank you so much.
private void ShareItem(File fileToShare) {
String package_name = "com.lucagrillo.myapp";
Uri uri = FileProvider.getUriForFile(this, package_name + ".fileprovider", fileToShare);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.putExtra(Intent.EXTRA_TEXT, "#myappHashtag");
shareIntent.setType(intentFormatType);
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share_with)));
}
Exception:
Writing exception to parcel
java.lang.SecurityException: Permission Denial: reading android.support.v4.content.FileProvider uri content://com.lucagrillo.myapp.fileprovider/images/shareFile.mp4?caption=%23myappHashtag from pid=9630, uid=10093 requires the provider be exported, or grantUriPermission()
at android.content.ContentProvider.enforceReadPermissionInner(ContentProvider.java:608)
at android.content.ContentProvider$Transport.enforceReadPermission(ContentProvider.java:483)
at android.content.ContentProvider$Transport.enforceFilePermission(ContentProvider.java:474)
at android.content.ContentProvider$Transport.openTypedAssetFile(ContentProvider.java:419)
at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:313)
at android.os.Binder.execTransact(Binder.java:565)
Manifest file provider:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.lucagrillo.myapp.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/filepaths" />
</provider>
You missed the call to addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) on your Intent. That will work if your minSdkVersion is 21 or higher, to grant rights to that Uri to whatever app handles the ACTION_SEND request.
If your minSdkVersion is below 21, you're going to have to grant rights to all possible ACTION_SEND handlers for your Intent. On those older devices, addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) only grants permission to the Uri that you would have in the "data" facet of the Intent (e.g., new Intent(Intent.ACTION_VIEW, uri)), not Uri values in extras.
You wind up with code looking a bit like this:
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) {
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
else {
List<ResolveInfo> resInfoList=
getPackageManager()
.queryIntentActivities(i, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
grantUriPermission(packageName, outputUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
(where i is the Intent and outputUri is the Uri you put in the extra)
Also, as a reminder: ACTION_SEND implementations are not obligated to support both EXTRA_TEXT and EXTRA_STREAM.
Related
This question already has answers here:
Permission Denial with File Provider through intent
(4 answers)
Closed 11 months ago.
I am trying to share file with FileProvider. I checked that file is shared properly with apps like Gmail, Google Drive etc. Even though following exception is thrown:
2019-08-28 11:43:03.169 12573-12595/com.example.name E/DatabaseUtils: Writing exception to parcel
java.lang.SecurityException: Permission Denial: reading androidx.core.content.FileProvider uri content://com.example.name.provider/external_files/Android/data/com.example.name/files/allergy_report.pdf from pid=6005, uid=1000 requires the provider be exported, or grantUriPermission()
at android.content.ContentProvider.enforceReadPermissionInner(ContentProvider.java:729)
at android.content.ContentProvider$Transport.enforceReadPermission(ContentProvider.java:602)
at android.content.ContentProvider$Transport.query(ContentProvider.java:231)
at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:104)
at android.os.Binder.execTransactInternal(Binder.java:1021)
at android.os.Binder.execTransact(Binder.java:994)
provider:
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_provider_paths" />
</provider>
file_provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="." />
</paths>
Sharing Intent
Intent intentShareFile = new Intent(Intent.ACTION_SEND);
File fileWithinMyDir = new File(targetPdf);
if (fileWithinMyDir.exists()) {
intentShareFile.setType("application/pdf");
Uri uri = FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + ".provider", fileWithinMyDir);
intentShareFile.putExtra(Intent.EXTRA_STREAM, uri);
intentShareFile.putExtra(Intent.EXTRA_SUBJECT, "Sharing File...");
intentShareFile.putExtra(Intent.EXTRA_TEXT, "Sharing File...");
intentShareFile.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(intentShareFile, "Share File"));
}
Hopefully you can point out my mistake why this exceptions is thrown when it seems like apps are granted permission properly and sharing works as it should be.
EDIT:
I found that the problem lies in line:
startActivity(Intent.createChooser(intentShareFile, "Share File"));
When I changed it simply to
startActivity(intentShareFile);
However it displays a little bit different layout for picking application. But still I cannot figure out why original chooser is not working.
Sorry about the late response. I solved it like this:
Intent chooser = Intent.createChooser(intentShareFile, "Share File");
List<ResolveInfo> resInfoList = this.getPackageManager().queryIntentActivities(chooser, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
this.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
startActivity(chooser);
This helped me: Permission Denial with File Provider through intent
There is also a way to grant the URI permission through the Intent flag, without doing in manually with grantUriPermission() and by keeping the usage of Intent.createChooser().
The Intent.createChooser() documentation states:
If the target intent has specified FLAG_GRANT_READ_URI_PERMISSION or FLAG_GRANT_WRITE_URI_PERMISSION, then these flags will also be set in the returned chooser intent, with its ClipData set appropriately: either a direct reflection of getClipData() if that is non-null, or a new ClipData built from getData().
Therefore, if the original Intent has the Uri set in its ClipData or in setData(), it should work as wanted.
In your example, the ACTION_SEND Intent supports the Uri set through setClipData() as of Jelly Bean (Android 4.1).
Long story short, here is a working example of your code:
Intent intentShareFile = new Intent(Intent.ACTION_SEND);
File fileWithinMyDir = new File(targetPdf);
if(fileWithinMyDir.exists()) {
String mimeType = "application/pdf";
String[] mimeTypeArray = new String[] { mimeType };
intentShareFile.setType(mimeType);
Uri uri = FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + ".provider", fileWithinMyDir);
// Add the uri as a ClipData
intentShareFile.setClipData(new ClipData(
"A label describing your file to the user",
mimeTypeArray,
new ClipData.Item(uri)
));
// EXTRA_STREAM is kept for compatibility with old applications
intentShareFile.putExtra(Intent.EXTRA_STREAM, uri);
intentShareFile.putExtra(Intent.EXTRA_SUBJECT,
"Sharing File...");
intentShareFile.putExtra(Intent.EXTRA_TEXT, "Sharing File...");
intentShareFile.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(intentShareFile, "Share File"));
}
In addition to the answer of Nit above, it is possible to set the ClipData directly with the to be shared uri as follows.
intent.setClipData(ClipData.newRawUri("", uri));
This prevents the security exception when presenting the intent chooser.
If you want to share multiple uris, you can set the clipdata with multiple uris to prevent the security exception. To summarize:
Intent intent = new Intent();
intent.setType(mimeType);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (uris.size() == 0) {
return;
}
else if (uris.size() == 1) {
Uri uri = uris.get(0);
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setClipData(ClipData.newRawUri("", uri));
}
else {
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
ClipData clipData = ClipData.newRawUri("", uris.get(0));
for (int i = 1; i < uris.size(); i++) {
Uri uri = uris.get(i);
clipData.addItem(new ClipData.Item(uri));
}
intent.setClipData(clipData);
}
startActivity(Intent.createChooser(intent, title));
This worked for me.
Intent sharableIntent = new Intent();
sharableIntent.setAction(Intent.ACTION_SEND);
sharableIntent.setFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION );
Uri imageUri = Uri.parse(ImgLoc);
File imageFile = new File(String.valueOf(imageUri));
Uri UriImage = FileProvider.getUriForFile(context, Author, imageFile);
sharableIntent.setType("image/*");
sharableIntent.putExtra(Intent.EXTRA_STREAM, UriImage);
sharableIntent.putExtra(Intent.EXTRA_TITLE, title);
sharableIntent.putExtra(Intent.EXTRA_TEXT, body);
Intent chooser = Intent.createChooser(sharableIntent, "Chooser Title");
chooser.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
context.startActivity(chooser);
createChooser
Intent.createChooser():Builds a new ACTION_CHOOSER Intent that wraps the given target intent, also optionally supplying a title. If the target intent has specified FLAG_GRANT_READ_URI_PERMISSION or FLAG_GRANT_WRITE_URI_PERMISSION, then these flags will also be set in the returned chooser intent, with its ClipData set appropriately: either a direct reflection of getClipData() if that is non-null, or a new ClipData built from getData()
I would like to share a file from internal directory.
I already use file provider.
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.gps.stuttgartuni.bincalendar"
android:exported="true"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_path" />
</provider>
and I share the file like this
File file = new File(getFilesDir(), fileName);
if(file.exists()){
try {
Uri uri =FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID, file);
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("application/xml");
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Context context=getApplicationContext();
List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(sharingIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
context.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
startActivity(sharingIntent);
}
catch (Exception e){
Log.e("Error",e.getMessage());
}
I am trying to send .xml
The code has no problems with sending e-mail using gmail and build in client, but I can't share the file using what's app or messenger, or any other messaging app.
Same messenger apps show the toast that the format is unsupported although normally I can send .xml file using them.
Any idea why the code has problem only with some apps?
This happen because you are set sharingIntent.setType("application/xml"); and not all apps can handle your intent. Change your type to sharingIntent.setType("text/plain");
In My App, I have given all permissions like storage, contact etc to app (Given run time permission for marshmallow and above version), but still app shows black screen for some mobile phone.
Permission Denial: opening provider
android.support.v4.content.FileProvider from ProcessRecord{bd58bf1
15489:com.google.android.apps.pdfviewer/u0a213} (pid=15489, uid=10213)
That is not exported from uid 10227.
//Code
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri photoURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider",
pdfFile);
Intent objIntent = new Intent(Intent.ACTION_VIEW);
List<ResolveInfo> resolvedIntentActivities = context.getPackageManager().queryIntentActivities(objIntent,
PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolvedIntentInfo : resolvedIntentActivities) {
String packageName = resolvedIntentInfo.activityInfo.packageName;
context.grantUriPermission(packageName, photoURI, Intent.FLAG_GRANT_WRITE_URI_PERMISSION |
Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
objIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
objIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
objIntent.setDataAndType(photoURI, "application/pdf");
context.startActivity(objIntent);
}else{
Uri path = Uri.fromFile(pdfFile);
Intent objIntent = new Intent(Intent.ACTION_VIEW);
objIntent.setDataAndType(path, "application/pdf");
objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(objIntent);
}`
[Screen]
Hi actually there might be some issue with accessing the FILE URI as it doesnt have the write read uri permission while raising the intent.
check the following thread.. Android - file provider - permission denial
hope you will get some idea.
Also post the code here to understand more.
I searched and read android developer files but I did not find any satisfactory answer for content provider grant uri permission. Can anybody explain more detailed and more simple. My questions are:
What grant uri is using for?
What is the differences between grant uri permission true and false
When we should use true? when false?
and any more detail are appreciated.
What grant uri is using for?
The "grant Uri permissions" feature allows you to have a ContentProvider that is normally inaccessible by third parties, yet selectively allow access to individual Uri values to individual third-party apps for a short period of time (e.g., long enough to view the PDF that the provider serves).
What is the differences between grant uri permission true and false
android:grantUriPermissions="true" indicates that your Java code can use FLAG_GRANT_READ_URI_PERMISSION and FLAG_GRANT_WRITE_URI_PERMISSION for any Uri served by that ContentProvider.
android:grantUriPermissions="false" indicates that only the Uri values specified by child <grant-uri-permission> elements can be used with FLAG_GRANT_READ_URI_PERMISSION and FLAG_GRANT_WRITE_URI_PERMISSION.
Say you need to mail some file that is on your application cache directory.
No other apps can access that file, unless you specify that other apps can access content of your application. For this you create content provider, and say, all uri's in form content://com.your.app/file you 'redirect' to your application cache directory.
Some code:
File f = ...; // Some local file.
Uri uri = Uri.parse("content://com.your.app/" + f.getName());
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, "Body");
intent.putExtra(Intent.EXTRA_STREAM, uri);
// You only can add flag FLAG_GRANT_READ_URI_PERMISSION if your app has
// android:grantUriPermissions="true" in manifest or see quote below.
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(intent, "Send Email"));
As CommonsWare said:
android:grantUriPermissions="false" indicates that only the Uri values
specified by child <grant-uri-permission> elements can be used with
FLAG_GRANT_READ_URI_PERMISSION and FLAG_GRANT_WRITE_URI_PERMISSION.
with adapter class and In Kotlin :-
val uri: Uri? = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID, file)
val sharingIntent = Intent(Intent.ACTION_SEND)
sharingIntent.type = "image/*"
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Images ")
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri)
val chooser = Intent.createChooser(sharingIntent, "Share File")
val resInfoList: List<ResolveInfo> = mContext.packageManager
.queryIntentActivities(chooser, PackageManager.MATCH_DEFAULT_ONLY)
for (resolveInfo in resInfoList) {
val packageName = resolveInfo.activityInfo.packageName
mContext.grantUriPermission(
packageName,
uri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION
)
}
mContext.startActivity(chooser)
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 on the docs,
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.supportv4.my_files"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/my_paths" />
</provider>
and using ShareCompat to share a file to other apps as follows:
ShareCompat.IntentBuilder.from(activity)
.setStream(uri) // uri from FileProvider
.setType("text/html")
.getIntent()
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
does not work, since the FLAG_GRANT_READ_URI_PERMISSION only grants permission for the Uri specified on the data of the intent, not the value of the EXTRA_STREAM extra (as was set by setStream).
I tried to compromise security by setting android:exported to true for the provider, but FileProvider internally checks if itself is exported, when so, it throws an exception.
Using FileProvider from support library you have to manually grant and revoke permissions(at runtime) for other apps to read specific Uri. Use Context.grantUriPermission and Context.revokeUriPermission methods.
For example:
//grant permision for app with package "packegeName", eg. before starting other app via intent
context.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
//revoke permisions
context.revokeUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
As a last resort, if you can't provide package name you can grant the permission to all apps that can handle specific intent:
//grant permisions for all apps that can handle given intent
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
...
List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
context.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
Alternative method according to the documentation:
Put the content URI in an Intent by calling setData().
Next, call the method Intent.setFlags() with either FLAG_GRANT_READ_URI_PERMISSION or FLAG_GRANT_WRITE_URI_PERMISSION
or both.
Finally, send the Intent to another app. Most often, you do this by calling setResult().
Permissions granted in an Intent remain in effect while the stack
of the receiving Activity is active. When the stack finishes, the
permissions are automatically removed. Permissions granted to one
Activity in a client app are automatically extended to other
components of that app.
Btw. if you need to, you can copy source of FileProvider and change attachInfo method to prevent provider from checking if it is exported.
Fully working code sample how to share file from inner app folder. Tested on Android 7 and Android 5.
AndroidManifest.xml
</application>
....
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="android.getqardio.com.gmslocationtest"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
</application>
xml/provider_paths
<?xml version="1.0" encoding="utf-8"?>
<paths>
<files-path
name="share"
path="external_files"/>
</paths>
Code itself
File imagePath = new File(getFilesDir(), "external_files");
imagePath.mkdir();
File imageFile = new File(imagePath.getPath(), "test.jpg");
// Write data in your file
Uri uri = FileProvider.getUriForFile(this, getPackageName(), imageFile);
Intent intent = ShareCompat.IntentBuilder.from(this)
.setStream(uri) // uri from FileProvider
.setType("text/html")
.getIntent()
.setAction(Intent.ACTION_VIEW) //Change if needed
.setDataAndType(uri, "image/*")
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
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:
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.package.name.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
file_paths.xml:
<paths>
<files-path name="app_directory" path="directory/"/>
</paths>
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<ResolveInfo> 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.
Since as Phil says in his comment on the original question, this is unique and there is no other info on SO on in google, I thought I should also share my results:
In my app FileProvider worked out of the box to share files using the share intent. There was no special configuration or code necessary, beyond that to setup the FileProvider. In my manifest.xml I placed:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.my.apps.package.files"
android:exported="false"
android:grantUriPermissions="true" >
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/my_paths" />
</provider>
In my_paths.xml I have:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="files" path="." />
</paths>
In my code I have:
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("application/xml");
Uri uri = FileProvider.getUriForFile(this, "com.my.apps.package.files", fileToShare);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share_file)));
And I am able to share my files store in my apps private storage with apps such as Gmail and google drive without any trouble.
As far as I can tell this will only work on newer versions of Android, so you will probably have to figure out a different way to do it. This solution works for me on 4.4, but not on 4.0 or 2.3.3, so this will not be a useful way to go about sharing content for an app that's meant to run on any Android device.
In manifest.xml:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.mydomain.myapp.SharingActivity"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
Take careful note of how you specify the authorities. You must specify the activity from which you will create the URI and launch the share intent, in this case the activity is called SharingActivity. This requirement is not obvious from Google's docs!
file_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="just_a_name" path=""/>
</paths>
Be careful how you specify the path. The above defaults to the root of your private internal storage.
In SharingActivity.java:
Uri contentUri = FileProvider.getUriForFile(getActivity(),
"com.mydomain.myapp.SharingActivity", myFile);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("image/jpeg");
shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Share with"));
In this example we are sharing a JPEG image.
Finally it is probably a good idea to assure yourself that you have saved the file properly and that you can access it with something like this:
File myFile = getActivity().getFileStreamPath("mySavedImage.jpeg");
if(myFile != null){
Log.d(TAG, "File found, file description: "+myFile.toString());
}else{
Log.w(TAG, "File not found!");
}
In my app FileProvider works just fine, and I am able to attach internal files stored in files directory to email clients like Gmail,Yahoo etc.
In my manifest as mentioned in the Android documentation I placed:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.package.name.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/filepaths" />
</provider>
And as my files were stored in the root files directory, the filepaths.xml were as follows:
<paths>
<files-path path="." name="name" />
Now in the code:
File file=new File(context.getFilesDir(),"test.txt");
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"Test");
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
new String[] {"email-address you want to send the file to"});
Uri uri = FileProvider.getUriForFile(context,"com.package.name.fileprovider",
file);
ArrayList<Uri> uris = new ArrayList<Uri>();
uris.add(uri);
shareIntent .putParcelableArrayListExtra(Intent.EXTRA_STREAM,
uris);
try {
context.startActivity(Intent.createChooser(shareIntent , "Email:").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
catch(ActivityNotFoundException e) {
Toast.makeText(context,
"Sorry No email Application was found",
Toast.LENGTH_SHORT).show();
}
}
This worked for me.Hope this helps :)
If you get an image from camera none of these solutions work for Android 4.4. In this case it's better to check versions.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getContext().getPackageManager()) != null) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
uri = Uri.fromFile(file);
} else {
uri = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".provider", file);
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, CAMERA_REQUEST);
}
grantUriPermission (from Android document)
Normally you should use Intent#FLAG_GRANT_READ_URI_PERMISSION or
Intent#FLAG_GRANT_WRITE_URI_PERMISSION with the Intent being used to
start an activity instead of this function directly. If you use this
function directly, you should be sure to call revokeUriPermission(Uri,
int) when the target should no longer be allowed to access it.
So I test and I see that.
If we use grantUriPermission before we start a new activity, we DON'T need
FLAG_GRANT_READ_URI_PERMISSION or FLAG_GRANT_WRITE_URI_PERMISSION in Intent to overcome SecurityException
If we don't use grantUriPermission. We need to use FLAG_GRANT_READ_URI_PERMISSION or FLAG_GRANT_WRITE_URI_PERMISSION to overcome SecurityException but
Your intent MUST contain Uri by setData or setDataAndType else SecurityException still throw. (one interesting I see: setData and setType can not work well together so if you need both Uri and type you need setDataAndType. You can check inside Intent code, currently when you setType, it will also set uri= null and when you setUri it will also set type=null)
just to improve answer given above:
if you are getting NullPointerEx:
you can also use getApplicationContext() without context
List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(takePictureIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
grantUriPermission(packageName, photoURI, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
I want to share something that blocked us for a couple of days: the fileprovider code MUST be inserted between the application tags, not after it.
It may be trivial, but it's never specified, and I thought that I could have helped someone!
(thanks again to piolo94)