How to share pdf and text through whatsapp in android? - android

I tried with the following code but it is not attaching the pdf file.
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.setType("text/plain");
if (isOnlyWhatsApp) {
sendIntent.setPackage("com.whatsapp");
}
Uri uri = Uri.fromFile(attachment);
sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
activity.startActivity(sendIntent);

I had this issue where I was trying to open a pdf file from assets folder and I did not work, but when I tried to open from Download folder (for example), it actually worked, and here is an example of it:
File outputFile = new File(Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_DOWNLOADS), "example.pdf");
Uri uri = Uri.fromFile(outputFile);
Intent share = new Intent();
share.setAction(Intent.ACTION_SEND);
share.setType("application/pdf");
share.putExtra(Intent.EXTRA_STREAM, uri);
share.setPackage("com.whatsapp");
activity.startActivity(share);

Please note If your targetSdkVersion is 24 or higher, we have to use FileProvider class to give access to the particular file or folder to make them accessible for other apps.
Step 1: add a FileProvider tag in AndroidManifest.xml under application tag.
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
Step 2:
then create a provider_paths.xml file in xml folder under res folder. Folder may be needed to create if it doesn't exist. The content of the file is shown below. It describes that we would like to share access to the External Storage at root folder (path=".") with the name external_files.
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
step 3: The final step is to change the line of code below in
Uri photoURI = Uri.fromFile(outputFile);
to
Uri uri = FileProvider.getUriForFile(PdfRendererActivity.this, PdfRendererActivity.this.getPackageName() + ".provider", outputFile);
step 4 (optional):
If using an intent to make the system open your file, you may need to add the following line of code:
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Hope this will help :)

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
pdfUri = FileProvider.getUriForFile(this, this.getPackageName() + ".provider", pdfFile);
} else {
pdfUri = Uri.fromFile(pdfFile);
}
Intent share = new Intent();
share.setAction(Intent.ACTION_SEND);
share.setType("application/pdf");
share.putExtra(Intent.EXTRA_STREAM, pdfUri);
startActivity(Intent.createChooser(share, "Share"));
If you are using Intent.createChooser then always open chooser

This works for me kotlin code.
var file =
File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"${invoiceNumber}.pdf"
)
if (file.exists()) {
val uri = if (Build.VERSION.SDK_INT < 24) Uri.fromFile(file) else Uri.parse(file.path)
val shareIntent = Intent().apply {
action = Intent.ACTION_SEND
type = "application/pdf"
putExtra(Intent.EXTRA_STREAM, uri)
putExtra(
Intent.EXTRA_SUBJECT,
"Purchase Bill..."
)
putExtra(
Intent.EXTRA_TEXT,
"Sharing Bill purchase items..."
)
}
startActivity(Intent.createChooser(shareIntent, "Share Via"))
}

I have used FileProvider because is a better approach.
First you need to add an xml/file_provider_paths resource with your private path configuration.
<paths>
<files-path name="files" path="/"/>
</paths>
Then you need to add the provider in your manifests
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="cu.company.app.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_provider_paths" />
</provider>
and finally in your Kotlin code
fun Context.shareFile(file: File) {
val context = this
val intent = Intent(Intent.ACTION_SEND).apply {
//file type, can be "application/pdf", "text/plain", etc
type = "*/*"
//in my case, I have used FileProvider, thats is a better approach
putExtra(
Intent.EXTRA_STREAM, FileProvider.getUriForFile(
context, "cu.company.app.provider",
file
)
)
//only whatsapp can accept this intente
//this is optional
setPackage("com.whatsapp")
}
try {
startActivity(Intent.createChooser(intent, getString(R.string.share_with)))
} catch (e: Exception) {
Toast.makeText(this, "We can't find WhatsApp", Toast.LENGTH_SHORT).show()
}
}

ACTION_VIEW is for viewing files. ACTION_VIEW will open apps which can handle pdf files in the list.
startActivity(new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.fromFile(reportFile), "application/pdf")));
I thought the ACTION_SEND intent would mean "send to other app" and not striktly "send somewhere else".

Try adding Intent.setType as follows:-
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
// sendIntent.setType("text/plain");
if (isOnlyWhatsApp) {
sendIntent.setPackage("com.whatsapp");
}
Uri uri = Uri.fromFile(attachment);
sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
sendIntent.setType("application/pdf");
activity.startActivity(sendIntent);

For sharing text, below you can find a good example, where you can share text with specific number if you would!
public static void openWhatsAppConversation(Activity activity, String number) {
boolean isWhatsappInstalled = isAppInstalled(activity, "com.whatsapp");
if (isWhatsappInstalled) {
Uri uri = Uri.parse("smsto:" + number);
Intent sendIntent = new Intent(Intent.ACTION_SENDTO, uri);
sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sendIntent.setPackage("com.whatsapp");
activity.startActivity(sendIntent);
} else {
ToastHelper.show(activity, "WhatsApp is not Installed!");
openMarket(activity, "com.whatsapp");
}
}

Try with following code
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
File pdfFile = new File(Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_DOWNLOADS), "Your file");
Uri uri = Uri.fromFile(pdfFile);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("application/pdf");
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, "Share via"));

go to file manager apps in android
and open it
then go to >>>data>>>data>>>com.whatsapp and then >>>share_prefs
open com.whatsapp_preference.xml file
search and select file >>>>name=document pdf ....< /string > and save this file
after >>>setting>>>>apps>>>>whatsapp>>>>and press force stop
new open whatsapp again and try to send or share your document

Related

Android send email with multiple attachment using file provider

Android App Problems sending an email with multiple attachments using File Provider.
I was using intent.putExtra(Intent.EXTRA_STREAM, Uri.parse( "file://"+csvFilePath)); and I have no issues sending single attachment file. Then I need to send multiple attachments. I have a problem to get it working.
In my AndroidManifest.xml I specify the provider with the following code :
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
Here is my xml/provider_paths
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="myfiles"
path="Android/data/com.example.abc/files/Documents"/>
</paths>
Send email code and files path are :
csvFilePath : /storage/emulated/0/Android/data/com.example.abc/files/Documents/Test123.csv
xyzFilePath : /storage/emulated/0/Android/data/com.example.abc/files/Documents/xyz123.txt
//attach multiple file
Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.setType("text/plain");
ArrayList<Uri> uris = new ArrayList<Uri>();
//uris.add(Uri.fromFile(new File(csvFilePath)));
//uris.add(Uri.fromFile(new File(xyzFilePath)));
// using file provider
File csvFile = new File(csvFilePath);
File xyzFile = new File(xyzFilePath);
uris.add(FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".provider", csvFile ));
uris.add(FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".provider", xyzFile ));
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
intent.setData(Uri.parse("mailto:" + abc#xyz.com));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
Exception raises during sending mailandroid.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.SEND_MULTIPLE dat=mailto:xxx.xxxxxxxx#xxxxx.xxx flg=0x10000001 clip={null U:content://com.example.abc.provider/myfiles/Test123.csv ...} (has extras) }
Found a solution with the following code :
xml/provider_paths
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
File baseDir = new File(Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_DOCUMENTS), "ABC");
if (!baseDir.exists()) {
baseDir.mkdirs();
}
Log.i("Debug", "baseDir " + baseDir.toString());
File f1 = new File(baseDir, "File1.txt");
writeToFile(f1, "This is file 1 contents 888888888");
Log.i("Debug", "f1 path" + f1.getAbsolutePath());
File f2 = new File(baseDir, "File2.txt");
writeToFile(f2, "This is file 2 contents 123456");
Log.i("Debug", "f2 path" + f2.getAbsolutePath());
String f1path = f1.toString();
String f2path = f2.toString();
string EXTRA_RECIPIENT = "janedoe#abc.com";
String message = "Test message 12345678 this is a test. ";
sendMail(f1path, f2path, message, EXTRA_RECIPIENT);
private void sendMail(String f1path, String f2path, String message, String mailTo) {
Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Test multiple attachments");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{mailTo});
File f1new = new File(f1path);
File f2new = new File(f2path);
ArrayList<Uri> uris = new ArrayList<Uri>();
uris.add(FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".provider", f1new ));
uris.add(FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".provider", f2new ));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(Intent.EXTRA_TEXT, message);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
startActivity(intent);
}
The gmail or mail sending apps may be disabled in your mobile. Kindly check the apps are enabled.
This ActivityNotFoundException occurs mainly when there is no application to handle the intent.
Then I need to send multiple attachments. I have a problem to get it
working.
Example for multiple attachments:
Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.setType("text/html");
intent.putExtra(Intent.EXTRA_SUBJECT, "Test multiple");
intent.putExtra(Intent.EXTRA_TEXT, "multiple attachments");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{recipient_address});
ArrayList<Uri> uris = new ArrayList<Uri>();
uris.add(Uri.fromFile(new File("/path/to/first/file")));
uris.add(Uri.fromFile(new File("/path/to/second/file")));
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
Finish with a call to startActivity() passing intent.

Permission Denial while sharing file with FileProvider [duplicate]

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()

Attach image using Intent.ACTION_SEND

I'm trying to attach an image using different applications with the following code:
val sendIntent = Intent(Intent.ACTION_SEND)
sendIntent.putExtra(Intent.EXTRA_TEXT, "Test example")
sendIntent.type = "image/png"
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(logo.absolutePath))
startActivity(sendIntent)
The image that is attached is generated with this code:
// Generate file for application logo
val path = Environment.getExternalStorageDirectory().absolutePath
val logo = File(path, "logo.png")
// If logo doesn't exist
if (!logo.exists())
{
// Create new file
logo.createNewFile()
// Save application logo to new file
val fOut = FileOutputStream(logo)
val image = BitmapFactory.decodeResource(applicationContext.resources, R.mipmap.ic_launcher_round)
image.compress(Bitmap.CompressFormat.PNG, 100, fOut)
fOut.flush()
fOut.close()
}
But when I try to open GMAIL with this intent, only text shows app with an error: Couldn't attach file.
What am I missing?
EDIT
Here is another solution: android.os.FileUriExposedException: file.jpg exposed beyond app through ClipData.Item.getUri()
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
From Android N you have to use FileProvider to Obtain Uri.
Please see below example for file sharing.
ArrayList<Uri> files = new ArrayList<Uri>();
File file = new File(<Your File Path>);
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(DetailActivity.this, BuildConfig.APPLICATION_ID + ".provider", file);
} else {
uri = Uri.fromFile(file);
}
files.add(uri);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putExtra(Intent.EXTRA_SUBJECT, "Product Sharing");
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_TEXT, "ANY TEXT MESSAGE");
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, files);
startActivity(intent);
Place below code in AndroidManifest.xml in Application tag
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/filepaths" />
</provider>
and place filepath.xml file in xml resource directory
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="."/>
</paths>
You cannot send file without file provider. Gmail, for example, doesn't request READ/WRITE_EXTERNAL_STORAGE permissions, so it cannot access your file. You must use file provider with GRANT_READ_URI_PERMISSION. You can read more here
https://developer.android.com/reference/android/support/v4/content/FileProvider
https://developer.android.com/training/secure-file-sharing/setup-sharing
https://developer.android.com/training/secure-file-sharing/share-file

Sharing documents via intent/Fileprovider

Problem 1: I have a pdf stored in
Environment.getExternalStorageDirectory() --> /storage/emulated/0/appname/downloads/sample.pdf
I'm sending it using normal way as shown:
File iconsStoragePath = Environment.getExternalStorageDirectory();
final String selpath = iconsStoragePath.getAbsolutePath() + "/appname/downloads/";
Intent intent = new Intent(Intent.ACTION_SEND);
Uri selectedUri = Uri.parse(selpath + "/" + item.getFilename());
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(selectedUri.toString());
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
intent.setType(mimeType);
intent.putExtra(Intent.EXTRA_STREAM, selectedUri);
startActivity(Intent.createChooser(intent, "Share File"));
Now the result is
The problem is file is sharing without the filename.
Problem 2: When I'm trying to use the file provider the pdf is not sharing gives me an error:
Unable to share. Please try again
Environment.getFilesDir() --> /data/data/com.myapp.name/files/myapp/downloads/sample.pdf
Manifest File:
<application>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/nnf_provider_paths" />
</provider>
</application>
xml/nnf_provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<files-path
name="root"
path="myapp/downloads" />
Code:
File path = new File(getFilesDir(), "downloads");
File file = new File(documentsPath + "/" + filename);
Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), AUTHORITY, file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, contentUri);
intent.setType("application/pdf");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
Which is the better way of doing it ?
I would personally prefer #2. Read this article on how to use ShareCompat to create ShareIntents
Regarding your problem with approach #2, I guess you're missing .setData or .setDataAndUri:
This is a sample snippet which works for me for sharing images via FileProviders:
public static void shareImage(Activity context) {
Log.d(TAG, "initializing share image");
File imgPath = new File(context.getCacheDir(), DEFAULT_TEMP_DIR_NAME);
File newFile = new File(imgPath, DEFAULT_TEMP_FILENAME);
String authority = context.getPackageName() + ".fileprovider";
Log.d(TAG, "authority: " + authority);
Uri contentUri = FileProvider.getUriForFile(context, authority, newFile);
if (contentUri != null) {
Intent shareIntent = ShareCompat.IntentBuilder.from(context)
.setType("image/png")
.setStream(contentUri)
.setSubject(context.getString(R.string.share_subject))
.setText(context.getString(R.string.share_message))
.setEmailTo(new String[]{"example#example.com"})
.getIntent();
shareIntent.setData(contentUri);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(Intent.createChooser(
shareIntent, context.getString(R.string.share_chooser_title)));
}
}

Open an image using URI in Android's default gallery image viewer

I have extracted image uri, now I would like to open image with Android's default image viewer. Or even better, user could choose what program to use to open the image. Something like File Explorers offer you if you try to open a file.
Accepted answer was not working for me,
What had worked:
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + "/sdcard/test.jpg"), "image/*");
startActivity(intent);
If your app targets Android N (7.0) and above, you should not use the answers above (of the "Uri.fromFile" method), because it won't work for you.
Instead, you should use a ContentProvider.
For example, if your image file is in external folder, you can use this (similar to the code I've made here) :
File file = ...;
final Intent intent = new Intent(Intent.ACTION_VIEW)//
.setDataAndType(VERSION.SDK_INT >= VERSION_CODES.N ?
FileProvider.getUriForFile(this,getPackageName() + ".provider", file) : Uri.fromFile(file),
"image/*").addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
manifest:
<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/provider_paths"/>
</provider>
res/xml/provider_paths.xml :
<?xml version="1.0" encoding="utf-8"?>
<paths>
<!--<external-path name="external_files" path="."/>-->
<external-path
name="files_root"
path="Android/data/${applicationId}"/>
<external-path
name="external_storage_root"
path="."/>
</paths>
If your image is in the private path of the app, you should create your own ContentProvider, as I've created "OpenFileProvider" on the link.
Ask myself, answer myself also:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("content://media/external/images/media/16"))); /** replace with your own uri */
It will also ask what program to use to view the file.
Try use it:
Uri uri = Uri.fromFile(entry);
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
String mime = "*/*";
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
if (mimeTypeMap.hasExtension(
mimeTypeMap.getFileExtensionFromUrl(uri.toString())))
mime = mimeTypeMap.getMimeTypeFromExtension(
mimeTypeMap.getFileExtensionFromUrl(uri.toString()));
intent.setDataAndType(uri,mime);
startActivity(intent);
Based on Vikas answer but with a slight modification: The Uri is received by parameter:
private void showPhoto(Uri photoUri){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(photoUri, "image/*");
startActivity(intent);
}
This thing might help if your working with android N and below
File file=new File(Environment.getExternalStorageDirectory()+"/directoryname/"+filename);
Uri path= FileProvider.getUriForFile(MainActivity.this,BuildConfig.APPLICATION_ID + ".provider",file);
Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path,"image/*");
intent.setFlags(FLAG_GRANT_READ_URI_PERMISSION | FLAG_GRANT_WRITE_URI_PERMISSION); //must for reading data from directory
A much cleaner, safer answer to this problem (you really shouldn't hard code Strings):
public void openInGallery(String imageId) {
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI.buildUpon().appendPath(imageId).build();
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
All you have to do is append the image id to the end of the path for the EXTERNAL_CONTENT_URI. Then launch an Intent with the View action, and the Uri.
The image id comes from querying the content resolver.
All the above answers not opening image.. when second time I try to open it show the gallery not image.
I got solution from mix of various SO answers..
Intent galleryIntent = new Intent(Intent.ACTION_VIEW, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setDataAndType(Uri.fromFile(mImsgeFileName), "image/*");
galleryIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(galleryIntent);
This one only worked for me..
The problem with showing a file using Intent.ACTION_VIEW, is that if you pass the Uri parsing the path. Doesn't work in all cases. To fix that problem, you need to use:
Uri.fromFile(new File(filePath));
Instead of:
Uri.parse(filePath);
Edit
Here is my complete code:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(mediaFile.filePath)), mediaFile.getExtension());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Info
MediaFile is my domain class to wrap files from database in objects.
MediaFile.getExtension() returns a String with Mimetype for the file extension. Example: "image/png"
Aditional code: needed for showing any file (extension)
import android.webkit.MimeTypeMap;
public String getExtension () {
MimeTypeMap myMime = MimeTypeMap.getSingleton();
return myMime.getMimeTypeFromExtension(MediaFile.fileExtension(filePath));
}
public static String fileExtension(String path) {
if (path.indexOf("?") > -1) {
path = path.substring(0, path.indexOf("?"));
}
if (path.lastIndexOf(".") == -1) {
return null;
} else {
String ext = path.substring(path.lastIndexOf(".") + 1);
if (ext.indexOf("%") > -1) {
ext = ext.substring(0, ext.indexOf("%"));
}
if (ext.indexOf("/") > -1) {
ext = ext.substring(0, ext.indexOf("/"));
}
return ext.toLowerCase();
}
}
Let me know if you need more code.
I use this it works for me
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), 1);
My solution using File Provider
private void viewGallery(File file) {
Uri mImageCaptureUri = FileProvider.getUriForFile(
mContext,
mContext.getApplicationContext()
.getPackageName() + ".provider", file);
Intent view = new Intent();
view.setAction(Intent.ACTION_VIEW);
view.setData(mImageCaptureUri);
List < ResolveInfo > resInfoList =
mContext.getPackageManager()
.queryIntentActivities(view, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo: resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
mContext.grantUriPermission(packageName, mImageCaptureUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
view.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(mImageCaptureUri, "image/*");
mContext.startActivity(intent);
}
Almost NO chance to use photo or gallery application(might exist one), but you can try the content-viewer.
Please checkout another answer to similar question here
My solution
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath()+"/your_app_folder/"+"your_picture_saved_name"+".png")), "image/*");
context.startActivity(intent);
The uri must be content uri not file uri,
You can get contentUri by FileProvider as
Uri contentUri = FileProvider.getUriForFile(getContext(),"com.github.myApp",curFile);
Don't forget adding provider in Manifest file.
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.github.myApp"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>

Categories

Resources