Opening a file with the default application (with permission enforcement) - android

My application has read and write permissions to the download folder. How to call the default application to open a file and give it the right to read the file?
When use this code, the default application opens, but cannot access the file:
public void openFile(String fileName)
{
String mimeType = URLConnection.guessContentTypeFromName(fileName);
Intent newIntent = new Intent(Intent.ACTION_VIEW);
Uri myUri = Uri.parse(fileName);
newIntent.setDataAndType(myUri, mimeType);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
newIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
newIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
try {
this.startActivity(newIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No handler for this type of file.", Toast.LENGTH_LONG).show();
}
}
Acrobat reader, for example, reports that there is no access to the file.
Only the GoogleFoto app when opened asked permission and successfully opened the picture.

Thanks to CommonsWare
android/AndroidManifest.xml
<!-- file provider for open attached files-->
<provider android:name="android.support.v4.content.FileProvider" android:authorities="XXX.XXXXXXXXXXXX" android:exported="false" android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="#xml/file_provider_paths"/>
</provider>
android/res/xml/file_provider_paths.xml
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<cache-path name="cache" path="/" />
<files-path name="files" path="/" />
</paths>
MainActivity.java
public String openFile(String filePath)
{
File file = new File(filePath);
if (!file.exists())
return "file not exist";
Uri uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID, file);
String mimeType = URLConnection.guessContentTypeFromName(filePath);
Intent newIntent = new Intent(Intent.ACTION_VIEW);
newIntent.setDataAndType(uri, mimeType);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
newIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
newIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
try {
this.startActivity(newIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No handler for this type of file.", Toast.LENGTH_LONG).show();
return "No handler for this type of file.";
}
return "";
}

Related

Opening a PDF file in Acrobat Reader

In my application I'd like to show a help file (PDF) to the user. The help file is published as asset and on first request copied to the external storage.
Adobe Acrobat Reader starts but does not show the file.
What am I missing ?
I use platform package 21 and Acrobat Reader 20.1.1 on Android 9.1.
Note: Via the file viewer I can see the file and on touching Adobe Acrobat Reader opens with the file.
Adobe Acrobat Reader is set as default application with option "Always".
Here is the code:
public static void open(Activity activity)
{
// copy help file to external storage
String filename = "helpfile.pdf";
File pubFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+filename);
if(!pubFile.exists())
{
InputStream ims = null;
try {
ims = activity.getAssets().open(filename);
Files.copy(ims, pubFile.toPath(),StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
if(ims != null)
{
try {
ims.close();
pubFile.delete();
} catch (IOException e1) {
e1.printStackTrace();
Toast.makeText(activity, "Failed to copy help file to accessible folder.", Toast.LENGTH_SHORT);
return;
}
}
e.printStackTrace();
Toast.makeText(activity, "Failed to copy help file to accessible folder.", Toast.LENGTH_SHORT);
return;
}
}
// open the help file with application for PDF files (Adobe Acrobat)
if(pubFile.exists() && pubFile.canRead())
{
// EDIT Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(pubFile));
Intent intent = new Intent(Intent.ACTION_VIEW, FileProvider.getUriForFile(activity
, "com.myapp.fileprovider"
, pubFile)); // EDIT
intent.setType("application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
PackageManager pm = activity.getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(intent, 0);
if (activities.size() > 0) {
activity.startActivity(intent);
} else {
Toast.makeText(activity, "No application to show help file.", Toast.LENGTH_SHORT);
}
}
}
EDIT
Here is what I did due to the recommendation of CommonsWare
Replaced Uri.fromFile(...) with FileProvider.getUriForFile(...) (see code above)
AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.myapp" android:versionCode="1" android:versionName="1.0">
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.myapp.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
</manifest>
src\android\res\xml\file_paths.xml:
<paths>
<external-path name="external" path="." />
</paths>

Android Problem with sharing temporary file

I' m trying to create a temporary file and share it.
So I created this class:
public class GenerateFile {
public static File writeToFile(Context mcoContext, String sBody) {
String fileName = "LOG FILE_" + String.valueOf(System.currentTimeMillis()) +".txt";
File file = new File(mcoContext.getCacheDir(), fileName);
try{
FileWriter writer = new FileWriter(file);
writer.append(sBody);
writer.flush();
writer.close();
return file;
}catch (Exception e){
Toast.makeText(mcoContext, "File write failed: " + e.toString(), Toast.LENGTH_LONG).show();
}
return null;
}
}
to generate a file that after I will share here:
String logContent = "123";
File filePath = new File(file.getAbsolutePath(), "external_files");
filePath.mkdir();
Uri uri = FileProvider.getUriForFile(StatusActivity.this, getPackageName(), filePath);
Intent intent = ShareCompat.IntentBuilder.from(StatusActivity.this)
.setStream(uri) // uri from FileProvider
.setType("text/html")
.getIntent()
.setAction(Intent.ACTION_VIEW) //Change if needed
.setDataAndType(uri, "text/*")
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
And in the manifest there are already this permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="com.sec.android.provider.badge.permission.WRITE"/>
<uses-permission android:name="com.sec.android.provider.badge.permission.READ"/>
and the provider declaration
<provider
android:name="android.support.v4.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>
The provider_paths class is defined in this way:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<files-path
name="share"
path="external_files"/>
</paths>
But it generate the message, when I try to share it by mail or telegram "Unable to attach file" or "Unsupported attachment". Also it seems to me that the file is not created.
Other apps do not have access to your app's getCacheDir(). FLAG_GRANT_READ_URI_PERMISSION and FLAG_GRANT_WRITE_URI_PERMISSION are for content Uri values, not file Uri values. And, on Android 7.0+ devices, your code should crash with a FileUriExposedException.
Use FileProvider to make your content available to other apps, and use FileProvider.getUriForFile() to get the Uri to put in the Intent.
So I follow the suggestion of #CommonsWare, and I edited my code. This is the final result:
public class GenerateFile {
public static Uri getFileURI(Context context, String nameFile, String content, String fileExtension) {
DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd");
Date date = new Date();
String fileName = dateFormat.format(date)+nameFile+fileExtension;
File file = new File(context.getCacheDir(), fileName);
try{
FileWriter writer = new FileWriter(file);
writer.append(content);
writer.flush();
writer.close();
//Toast.makeText(context, "Writing to the file completed successfully", Toast.LENGTH_LONG).show();
}catch (Exception e){
Toast.makeText(context, "File writing failed: " + e.toString(), Toast.LENGTH_LONG).show();
}
File filePath = new File(context.getCacheDir(), "");
File newFile = new File(filePath, fileName);
return FileProvider.getUriForFile(context, "MYPACKAGE.fileprovider", newFile);
}
}
and in another class:
private void sendFile(String nameFile, String logContent, String fileExtension) {
Uri contentUri = GenerateFile.getFileURI(getApplicationContext(), nameFile, logContent, fileExtension);
Intent intent = ShareCompat.IntentBuilder.from(StatusActivity.this)
.setStream(contentUri) // uri from FileProvider
.setType("text/plain")
.getIntent()
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(intent, "send"));
}
so to send the file. I also deleted the permission (previously mentioned) in the manifest, because I didn't need it anymore.
And I also edited my provider and provider_path file like that:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="MYPACKAGE.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>
<?xml version="1.0" encoding="utf-8"?>
<cache-path
name="my_files"
path=""
/>
Now it works! Thank you very much guys for the help!
Did you specifically ask the user for those permissions? It's not enough to just put the permissions in the manifest for target sdks below 28. Also, in Android Q, you will need to work around external storage permissions altogether as this is disallowed.

Unable to launch a PDF viewer in Nougat (7.1)

I am creating a app in which i am generating pdf and after this app showing PDF automatically. it is working wee in 6.1 android but not showing in android 7.1. my code is
public void showPDF() {
File pdfFile = new File(Environment.getExternalStorageDirectory() , "A_DailyRegiser.pdf");
try {
if (pdfFile.exists()) {
Uri path = Uri.fromFile(pdfFile);
Intent objIntent = new Intent(Intent.ACTION_VIEW);
objIntent.setDataAndType(path, "application/pdf");
// objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
objIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
objIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(objIntent);
} else {
Toast.makeText(dailycollection.this, "File NotFound",Toast.LENGTH_SHORT).show();
}
} catch (ActivityNotFoundException e) {
Toast.makeText(dailycollection.this,
"No Viewer Application Found", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
That's because of the new changes in Noughat API's Read more here
you are suggested to use the content:// scheme instead of file:// for this we can use the file provider API.
here is sample code:
<manifest>
...
<application>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.mydomain.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
...
</application>
define the scope of your access
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="my_images" path="images/"/>
Generating the Content URI for a File
File imagePath = new File(Context.getFilesDir(), "images");
File newFile = new File(imagePath, "default_image.jpg");
Uri contentUri = getUriForFile(getContext(), "com.mydomain.fileprovider", newFile);
Granting Temporary Permissions to a URI
Intent.setFlags() with either FLAG_GRANT_READ_URI_PERMISSION or FLAG_GRANT_WRITE_URI_PERMISSION or both.
read more here

FileProvider can't open file

I'm struggling with FileProvider. Even following this Google documentation and this post that is pretty much the same as my problem.
So I'm trying to open a pdf file from external storage. The directory is "Download/nst". I provided the path in file_paths.xml
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="br.com.myapp.bomapp"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"/>
</provider>
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="Download" path="Download/" />
</paths>
This is how I get pdf path:
private File getPdfFile(long workOrderId){
File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS+"/nst/"+workOrderId);
String[] filesNames = downloads.list(
new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return name.endsWith(".pdf");
}
}
);
if(filesNames.length > 0){
return new File(downloads, filesNames[0]);
}
return null;
}
And this is how I open pdf:
File pdf = getPdfFile(workOrder.getId());
if(pdf == null){
view.showError(context.getString(R.string.error_no_pdf_found));
return;
}
Intent target = new Intent(Intent.ACTION_VIEW);
Uri fileUri;
if(Build.VERSION.SDK_INT >= 24){
fileUri = FileProvider.getUriForFile(context, "br.com.myapp.bomapp", pdf);
target.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION|Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
else{
fileUri = Uri.fromFile(pdf);
}
target.setDataAndType(fileUri,"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
view.showError(context.getString(R.string.error_no_pdf_reader_found));
}
Notice I'm using Intent.FLAG_GRANT_READ_URI_PERMISSION.
When debugging the getPdfFile method returns this path for me:
new File(downloads, fileNames[0])": "fileNames[0]=/storage/emulated/0/Download/nst/12345/myName.pdf"
And FileProvider gets me this:
"fileUri = content://br.com.myapp.bomapp/Download/nst/12345/myFile.pdf"
When 12345 is a sub directory which the file is located.
After the file directory is passed to FileProvider it opens the file but screen gets black because file is not there.
But when it is opened with Uril.fromFile the file is shown.
Am I doing something wrong?

Create and Share a File from Internal Storage

My goal is to create a XML file on internal storage and then send it through the share Intent.
I'm able to create a XML file using this code
FileOutputStream outputStream = context.openFileOutput(fileName, Context.MODE_WORLD_READABLE);
PrintStream printStream = new PrintStream(outputStream);
String xml = this.writeXml(); // get XML here
printStream.println(xml);
printStream.close();
I'm stuck trying to retrieve a Uri to the output file in order to share it. I first tried to access the file by converting the file to a Uri
File outFile = context.getFileStreamPath(fileName);
return Uri.fromFile(outFile);
This returns file:///data/data/com.my.package/files/myfile.xml but I cannot appear to attach this to an email, upload, etc.
If I manually check the file length, it's proper and shows there is a reasonable file size.
Next I created a content provider and tried to reference the file and it isn't a valid handle to the file. The ContentProvider doesn't ever seem to be called a any point.
Uri uri = Uri.parse("content://" + CachedFileProvider.AUTHORITY + "/" + fileName);
return uri;
This returns content://com.my.package.provider/myfile.xml but I check the file and it's zero length.
How do I access files properly? Do I need to create the file with the content provider? If so, how?
Update
Here is the code I'm using to share. If I select Gmail, it does show as an attachment but when I send it gives an error Couldn't show attachment and the email that arrives has no attachment.
public void onClick(View view) {
Log.d(TAG, "onClick " + view.getId());
switch (view.getId()) {
case R.id.share_cancel:
setResult(RESULT_CANCELED, getIntent());
finish();
break;
case R.id.share_share:
MyXml xml = new MyXml();
Uri uri;
try {
uri = xml.writeXmlToFile(getApplicationContext(), "myfile.xml");
//uri is "file:///data/data/com.my.package/files/myfile.xml"
Log.d(TAG, "Share URI: " + uri.toString() + " path: " + uri.getPath());
File f = new File(uri.getPath());
Log.d(TAG, "File length: " + f.length());
// shows a valid file size
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("text/plain");
startActivity(Intent.createChooser(shareIntent, "Share"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
break;
}
}
I noticed that there is an Exception thrown here from inside createChooser(...), but I can't figure out why it's thrown.
E/ActivityThread(572): Activity
com.android.internal.app.ChooserActivity has leaked IntentReceiver
com.android.internal.app.ResolverActivity$1#4148d658 that was
originally registered here. Are you missing a call to
unregisterReceiver()?
I've researched this error and can't find anything obvious. Both of these links suggest that I need to unregister a receiver.
ChooserActivity has leaked IntentReceiver
Why does Intent.createChooser() need a BroadcastReceiver and how to implement?
I have a receiver setup, but it's for an AlarmManager that is set elsewhere and doesn't require the app to register / unregister.
Code for openFile(...)
In case it's needed, here is the content provider I've created.
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
String fileLocation = getContext().getCacheDir() + "/" + uri.getLastPathSegment();
ParcelFileDescriptor pfd = ParcelFileDescriptor.open(new File(fileLocation), ParcelFileDescriptor.MODE_READ_ONLY);
return pfd;
}
It is possible to expose a file stored in your apps private directory via a ContentProvider. Here is some example code I made showing how to create a content provider that can do this.
Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.providertest"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="11" android:targetSdkVersion="15" />
<application android:label="#string/app_name"
android:icon="#drawable/ic_launcher"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="MyProvider"
android:authorities="com.example.prov"
android:exported="true"
/>
</application>
</manifest>
In your ContentProvider override openFile to return the ParcelFileDescriptor
#Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
File cacheDir = getContext().getCacheDir();
File privateFile = new File(cacheDir, "file.xml");
return ParcelFileDescriptor.open(privateFile, ParcelFileDescriptor.MODE_READ_ONLY);
}
Make sure you have copied your xml file to the cache directory
private void copyFileToInternal() {
try {
InputStream is = getAssets().open("file.xml");
File cacheDir = getCacheDir();
File outFile = new File(cacheDir, "file.xml");
OutputStream os = new FileOutputStream(outFile.getAbsolutePath());
byte[] buff = new byte[1024];
int len;
while ((len = is.read(buff)) > 0) {
os.write(buff, 0, len);
}
os.flush();
os.close();
is.close();
} catch (IOException e) {
e.printStackTrace(); // TODO: should close streams properly here
}
}
Now any other apps should be able to get an InputStream for your private file by using the content uri (content://com.example.prov/myfile.xml)
For a simple test, call the content provider from a seperate app similar to the following
private class MyTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
Uri uri = Uri.parse("content://com.example.prov/myfile.xml");
InputStream is = null;
StringBuilder result = new StringBuilder();
try {
is = getApplicationContext().getContentResolver().openInputStream(uri);
BufferedReader r = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = r.readLine()) != null) {
result.append(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try { if (is != null) is.close(); } catch (IOException e) { }
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(CallerActivity.this, result, Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
}
So Rob's answer is correct I assume but I did it a bit differently. As far as I understand, with the setting in in provider:
android:exported="true"
you are giving public access to all your files?! Anyway, a way to give only access to some files is to define file path permissions in the following way:
<provider
android:authorities="com.your.app.package"
android:name="android.support.v4.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
and then in your XML directory you define file_paths.xml file as follows:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path path="/" name="allfiles" />
<files-path path="tmp/" name="tmp" />
</paths>
now, the "allfiles" gives the same kind of public permission I guess as the option android:exported="true" but you don't really want that I guess so to define a subdirectory is the next line. Then all you have to do is store the files you want to share, there in that dir.
Next what you have to do is, as also Rob says, obtain a URI for this file. This is how I did it:
Uri contentUri = FileProvider.getUriForFile(context, "com.your.app.package", sharedFile);
Then, when I have this URI, I had to attach to it permissions for other app to use it. I was using or sending this file URI to camera app. Anyway this is the way how I got the other app package info and granted permissions to the URI:
PackageManager packageManager = getPackageManager();
List<ResolveInfo> list = packageManager.queryIntentActivities(cameraIntent, PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() < 1) {
return;
}
String packageName = list.get(0).activityInfo.packageName;
grantUriPermission(packageName, sharedFileUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
ClipData clipData = ClipData.newRawUri("CAMFILE", sharedFileUri);
cameraIntent.setClipData(clipData);
cameraIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
cameraIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(cameraIntent, GET_FROM_CAMERA);
I left the code for camera as I did not want to take some other example I did not work on. But this way you see that you can attach permissions to URI itself.
The camera's thing is that I can set it via ClipData and then additionally set permissions. I guess in your case you only need FLAG_GRANT_READ_URI_PERMISSION as you are attaching a file to an email.
Here is the link to help on FileProvider as I based all of my post on the info I found there. Had some trouble finding a package info for camera app though.
Hope it helps.
None of the above answers helped. My problem was the point of passing intent extras but I'll walk you through all the steps to share a file.
Step 1: Create a Content Provider
This will make the file accessible to whichever app you want to share with.
Paste the following in the Manifest.xml file inside the <application></applicatio> tags
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="{YOUR_PACKAGE_NAME}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>
Step 2: Define paths accessible by the content provider
Do this by creating a file called provider_paths.xml (or a name of your choice) under res/xml. Put the following code in the file
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external"
path="." />
<external-files-path
name="external_files"
path="." />
<cache-path
name="cache"
path="." />
<external-cache-path
name="external_cache"
path="." />
<files-path
name="files"
path="." />
</paths>
Step 3: Create the Intent to share the file
Intent intentShareFile = new Intent(Intent.ACTION_SEND);
Uri uri = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".fileprovider", fileToShare);
intentShareFile.setDataAndType(uri, URLConnection.guessContentTypeFromName(fileToShare.getName()));
//Allow sharing apps to read the file Uri
intentShareFile.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//Pass the file Uri instead of the path
intentShareFile.putExtra(Intent.EXTRA_STREAM,
uri);
startActivity(Intent.createChooser(intentShareFile, "Share File"));
If you need to permission other apps to see your app's private files (for Share, or otherwise) you might be able to save some time and just use v4 compat library's FileProvider
This is what i'm using:
I combined some answers and used the current AndroidX Doku:
Sharing files Android Development
Basic Process: You change the manifest to make it possible for other apps to access your local files. the filepath's that are allowed to be accessed from outside are found in the res/xml/filepaths.xml. When sharing you create an intent to share and set a Flag that temporarily allowed the other app to access your local files. Android documentation claims this is the secure way to share files
Step1: Add FileProvider to Manifest
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.YOUR.APP.PACKAGE.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/filepaths" />
</provider>
Step2: Add filepaths.xml to res/xml (if XML folder does not exists just create it yourself)
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path path="share/" name="share" />
</paths>
Step3: Use a function like this to start a file share. this function moves the file to the predefined share folder and creates a Url to it. the ShareDir is the File pointing to the files/share/ directory. the copy_File function copies the given file to the share directory in order to be accessible from the outside.
The function also makes it possible to Send the File as email with given header and body. if not needed just set it to empty strings
public void ShareFiles(Activity activity, List<File> files, String header, String body) {
ArrayList<Uri> uriList = new ArrayList<>();
if(files != null) {
for (File f : files) {
if (f.exists()) {
File file_in_share = copy_File(f, ShareDir);
if(file_in_share == null)
continue;
// Use the FileProvider to get a content URI
try {
Uri fileUri = FileProvider.getUriForFile(
activity,
"com.YOUR.APP.PACKAGE.fileprovider",
file_in_share);
uriList.add(fileUri);
} catch (IllegalArgumentException e) {
Log.e("File Selector",
"The selected file can't be shared: " + f.toString());
}
}
}
}
if(uriList.size() == 0)
{
Log.w("StorageModule", "ShareFiles: no files to share");
return;
}
Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setType("text/html");
intent.putExtra(Intent.EXTRA_SUBJECT, header);
intent.putExtra(Intent.EXTRA_TEXT, body);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uriList);
activity.startActivity(Intent.createChooser(intent, "Share Files"));
}

Categories

Resources