My question is how to share multiple files with ShareCompat intentBuilder in android.
My code throws exception:
android.content.ActivityNotFoundException: No Activity found to handle
Intent { act=android.intent.action.SEND_MULTIPLE flg=0x80001
pkg=com.google.android.gm (has clip) (has extras) }
My code is:
static void with(Activity activity, ArrayList<String> imageFile,String app){
ArrayList<Uri> imagesUri=new ArrayList<>();
for (String i:imageFile)
imagesUri.add(FileProvider.getUriForFile(
activity, FILES_AUTHORITY, new File(i)));
Intent shareIntent = ShareCompat.IntentBuilder.from(activity).getIntent();
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,imagesUri);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
activity.startActivity(shareIntent);
}
Is throws error for every app (package name).
the following works for me:
ShareCompat.IntentBuilder shareIntent = ShareCompat.IntentBuilder.from(activity).setType("image/*");
for(String address : addresses ) {
File file = new File(address);
Uri imageUri = FileProvider.getUriForFile(
activity,
"app.signature.fileprovider",
file);
shareIntent.addStream(imageUri);
}
Intent intent=shareIntent.getIntent();
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(intent, "Choose Application"));
you should use addStream() to add multiple files.
After a very hard time searching on sites like stackoverflow. I found a solution in #Ian Lake's blog post that works for me and makes sense too.
ShareCompat.IntentBuilder shareIntent = ShareCompat.IntentBuilder.from((Activity) context)
.setType("video/image/*");
String[] files = parentDirectory.list();
if (files != null) {
for (String address : files) {
File file = new File(address);
File filePath = new File(context.getExternalFilesDir(null), "vids"); //vids is a directory local to my app in i.e storage/0/emulated/Android/data/com.myapp.videoeditor/vids
File newFile = new File(filePath, file.getName());
if (address.contains("cut_video")) {
Uri uri = FileProvider.getUriForFile(
context,
"com.myapp.videoeditor.fileprovider",
newFile);
shareIntent.addStream(uri);
}
}
}
Intent intent = shareIntent.getIntent();
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(Intent.createChooser(intent, "Choose..."));
res/xml/file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-files-path name="external_files" path="vids/"/>
</paths>
Manifest
<application
....
....>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.myapp.videoeditor.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<!-- ressource file to create -->
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths">
</meta-data>
...
...
</application>
Did you add intent filter in AndroidManifest.xml for the activity that is supposed to receive the files?
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
Related
I used to attach a logs file, that I was storing in externalCacheDir, to a mail client.
Using this : intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(logFile))
However, starting from Android 11 it just stopped working. So I tried using FileProvider. But once the mail client opens it says "Couldn't attach file".
I have tried doing everything I could find here on SO and on the internet in general. But I can't seem to find the solution that will actually work.
Activity :
val logFile: File = File(globalContext.externalCacheDir, "MyLogFile.log")
fun Activity.openMail(
type: String = "text/plain"
): Boolean {
val intent = Intent(Intent.ACTION_SENDTO)
intent.putExtra(Intent.EXTRA_EMAIL, arrayOf("<some address...>"))
intent.putExtra(Intent.EXTRA_SUBJECT, "Android Logs")
intent.putExtra(Intent.EXTRA_TEXT, "some text")
val uri = FileProvider.getUriForFile(this, "${BuildConfig.APPLICATION_ID}.fileprovider", logFile)
intent.putExtra(Intent.EXTRA_STREAM, uri)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
intent.type = type
intent.data = Uri.parse("mailto:")
if (intent.resolveActivity(packageManager) != null) {
startActivity(Intent.createChooser(intent, "Send email via::"))
return true
} else {
return false
}
}
Manifest :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>
provider_paths :
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-cache-path name="external_cache" path="."/>
</paths>
I have read all of the similar posts in regards to sending an attachment from internal memory using the GMAIL app. I implemented the content provider suggestion and still cannot get the attachment to actually send using GMAIL.
When passing the intent, everything seems like it is working, the file just gets removed when sent and the recipient sees no attachments. This code works fine on the native Android Email application.
Any suggestions or comments are greatly appreciated.
Android Manifest:
<provider
android:authorities="com.myapp.fileprovider"
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>
file_paths.xml:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="/data/user/0/com.myapp/files" path="."/>
</paths>
java:
ShareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
File fileToSend = new File("");
File dir = getFilesDir();
File[] subFiles = dir.listFiles();
if (subFiles != null) {
for (File file : subFiles) {
if (file.getName().equals(curveChosen)) {
fileToSend = file;
}
}
}
File Path = new File(view.getContext().getFilesDir(),"");
File newFile = new File(Path,fileToSend.getName());
Uri contentUri = FileProvider.getUriForFile(view.getContext(),"com.myapp.fileprovider", newFile);
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
sendIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Email Subject");
sendIntent.putExtra(Intent.EXTRA_TEXT,"Email Text");
startActivity(Intent.createChooser(sendIntent,"Select Email Application"));
}
});
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)
I'm developing an Android application and I have to open some files.
This is my code using intent:
public class FacturaActivity extends Activity {
(...)
public void downloadInvoice(View view) {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
}
}
File is in the root directory of the SD card and I can manually open it.
Problem
Application is closed when it arrives at startActivity(intent). I think the problem is in AndroidManifest.xml file, but I don't know how to put it correctly.
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:name="###.MyApplication" > <!--cant show complete name-->
<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>
<activity
android:name=".FacturaActivity" >
</activity>
</application>
LogCat
07-03 15:49:13.094: E/AndroidRuntime(1032): FATAL EXCEPTION: main
07-03 15:49:13.094: E/AndroidRuntime(1032): java.lang.IllegalStateException: Could not execute method of the activity
(...)
07-03 15:49:13.094: E/AndroidRuntime(1032): Caused by: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=file:///mnt/sdcard/201209_F2012212782.PDF typ=application/pdf flg=0x40000000 }
07-03 15:49:13.094: E/AndroidRuntime(1032): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1408)
07-03 15:49:13.094: E/AndroidRuntime(1032): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1378)
07-03 15:49:13.094: E/AndroidRuntime(1032): at android.app.Activity.startActivityForResult(Activity.java:2817)
07-03 15:49:13.094: E/AndroidRuntime(1032): at android.app.Activity.startActivity(Activity.java:2923)
Can you help me to complete AndroidManifest? Or how can I open that pdf?
The problem is that there is no app installed to handle opening the PDF. You should use the Intent Chooser, like so:
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename);
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
As of API 24, sending a file:// URI to another app will throw a FileUriExposedException. Instead, use FileProvider to send a content:// URI:
public File getFile(Context context, String fileName) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return null;
}
File storageDir = context.getExternalFilesDir(null);
return new File(storageDir, fileName);
}
public Uri getFileUri(Context context, String fileName) {
File file = getFile(context, fileName);
return FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
}
You must also define the FileProvider in your manifest:
<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>
Example file_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="name" path="path" />
</paths>
Replace "name" and "path" as appropriate.
To give the PDF viewer access to the file, you also have to add the FLAG_GRANT_READ_URI_PERMISSION flag to the intent:
private void displayPdf(String fileName) {
Uri uri = getFileUri(this, fileName);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/pdf");
// FLAG_GRANT_READ_URI_PERMISSION is needed on API 24+ so the activity opening the file can read it
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (intent.resolveActivity(getPackageManager()) == null) {
// Show an error
} else {
startActivity(intent);
}
}
See the FileProvider documentation for more details.
String dir="/Attendancesystem";
public void displaypdf() {
File file = null;
file = new File(Environment.getExternalStorageDirectory()+dir+ "/sample.pdf");
Toast.makeText(getApplicationContext(), file.toString() , Toast.LENGTH_LONG).show();
if(file.exists()) {
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
}
else
Toast.makeText(getApplicationContext(), "File path is incorrect." , Toast.LENGTH_LONG).show();
}
Kotlin version below (Updated version of #paul-burke response:
fun openPDFDocument(context: Context, filename: String) {
//Create PDF Intent
val pdfFile = File(Environment.getExternalStorageDirectory().absolutePath + "/" + filename)
val pdfIntent = Intent(Intent.ACTION_VIEW)
pdfIntent.setDataAndType(Uri.fromFile(pdfFile), "application/pdf")
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
//Create Viewer Intent
val viewerIntent = Intent.createChooser(pdfIntent, "Open PDF")
context.startActivity(viewerIntent)
}
The reason you don't have permissions to open file is because you didn't grant other apps to open or view the file on your intent. To grant other apps to open the downloaded file, include the flag(as shown below): FLAG_GRANT_READ_URI_PERMISSION
Intent browserIntent = new Intent(Intent.ACTION_VIEW);
browserIntent.setDataAndType(getUriFromFile(localFile), "application/pdf");
browserIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION|
Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(browserIntent);
And for function:
getUriFromFile(localFile)
private Uri getUriFromFile(File file){
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
return Uri.fromFile(file);
}else {
return FileProvider.getUriForFile(itemView.getContext(), itemView.getContext().getApplicationContext().getPackageName() + ".provider", file);
}
}
Want to chime in with the answers above. The code is nearly identical, except it's in an Android Jetpack Compose composable (and therefore in Kotlin). That, and I did two videos talking through it.
Here's the happy path version, (clocking in at 10 minutes).
For the whole hog, this behemoth 30 minute screenshow has me provide a significant amount of context and a/b options of the code.
If you want to see the code, you can find it in this repo branch.
I want to open an image from internal folder with the android default image viewer, on the Nexus 7 tablet.
I use the following code,but for some reason the image is not displayed. What I'm doing wrong? The path to the file is :
file:///data/data/com.example.denandroidapp/files/Attachments/photoTemp/photo.jpg
(this is what Uri.parse("file://" + file) returns).
ArticlePhoto photo = new ArticlePhoto(soapObject);
File f = new File(context.getFilesDir() + "/Attachments/photoTemp");
if(!f.exists())
f.mkdirs();
if (photo.ArtPhoto != null) {
Bitmap articlePhoto = BitmapFactory.decodeByteArray(photo.ArtPhoto, 0, photo.ArtPhoto.length);
ByteArrayOutputStream bytesFile = new ByteArrayOutputStream();
articlePhoto.compress(Bitmap.CompressFormat.JPEG, 100, bytesFile);
File file = new File(f + "/photo.jpeg");
try {
if(!file.exists())
file.createNewFile();
FileOutputStream outStream = new FileOutputStream(file);
outStream.write(bytesFile.toByteArray());
outStream.close();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + file),"image/jpeg");
startActivity(intent);
} catch(Exception ex) {
AlertDialog alert = new AlertDialog.Builder(context).create();
alert.setTitle("Warning!");
alert.setMessage(ex.getMessage());
alert.show();
}
}
Try with this :
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
Uri uri = Uri.parse("file://" + file.getAbsolutePath());
intent.setDataAndType(uri,"image/*");
startActivity(intent);
Thanks.
The problem is that the image is internal to your application! So an external application (Image Viewer) has no access to the data that is internal to your application.
What you might have to do is create a Content Provider .
http://web.archive.org/web/20111020204554/http://www.marcofaion.it/?p=7
Android Manifest.xml
<provider android:authorities="com.example.denandroidapp" android:enabled="true" android:exported="true" android:name=<fully classified name of provider class>>
</provider>
Creating Intent
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.parse("content://com.example.denandroidapp/" + filename);
intent.setDataAndType(uri, "image/jpeg");
If a file is associated with your app (stored on the internal storage of your app space ), other apps can not access your file directly provided a valid file path. Instead, you have to create a file provider and generate a content uri.
First, add the file provider in your AndroidManifest.xml
<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>
Then you need to create an a file named file_paths in xml/file_paths.xml (the directory xml is not created by default, so create it).
file_paths.xml looks like
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="myFiles" path="./"/>
</paths>
add as much as paths you want your provider to access in .
atlast you need to create your intent
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
File imagePath = new File(context.getFilesDir(), "fileName");
Uri contentUri = FileProvider.getUriForFile(context, "com.mydomain.fileprovider", imagePath);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(contentUri,"image/*");
context.startActivity(intent);
Note: make sure the file path sepecefied in file_paths.xml and new File(context.getFilesDir(),"fileName"), matches. getFilesDir() will give you the root directory of your app.
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(outputFileName)),"image/jpeg");
startActivity(intent);
You can use FileProvider which extends ContentProvider
Check the link -
https://developer.android.com/reference/android/support/v4/content/FileProvider
To specify the FileProvider component itself, add a "provider" element to your app manifest.
<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>
You must specify a child element of "paths" for each directory that contains files for which you want content URIs. For example, these XML elements specify two directories
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="my_images" path="images/"/>
<files-path name="my_docs" path="docs/"/>
</paths>
After this you need to generate content URI for the file and then call the intent, refer the below link
https://developer.android.com/reference/android/support/v4/content/FileProvider#GetUri
Check this: https://stackoverflow.com/a/11088980/1038442;
File file = new File(filePath);
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());
String type = map.getMimeTypeFromExtension(ext);
if (type == null)
type = "*/*";
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.fromFile(file);
intent.setDataAndType(data, type);
startActivity(intent);
PS: if your are trying to open .jpg files, try to
Replace String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());
With String ext = MimeTypeMap.getFileExtensionFromUrl(".jpg");
Good luck.
In my case, The gallery launched but did not show any images and went straight to the home page. My situation is quite different from what OP faced but I think it's worth mentioning here since the question is about images not being shown through implicit intent.
My problem came from the code below.
val intent = context.packageManager.getLaunchIntentForPackage(packageName ?: "")
The code above tells PackageManager to launch the entry point of the application, instead of the activity that shows the images.
If you look at the Logcat above, you can find that the intent launched with cat=[android.intent.category.Launcher] will go to SplashActivity. This happened because I created the intent with getLaunchIntentForPackage()
Alternative is to use Intent with setPackage() like the code in below
val intent = Intent()
val uri = Uri.fromFile(file) // You should probably replace with ContentProvider's uri
intent.apply {
flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
action = Intent.ACTION_VIEW
setPackage(packageName)
setDataAndType(uri, "image/*")
}
context.startActivity(intent)