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

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>

Related

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

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)));
}
}

Intent to open PDF file in Android N

I have been trying to open a PDF file using the intent. It works fine for devices prior to Adroid N. Following is the code I have used
File file = new File(gridItems.get(position).getPath());
Intent intent = null;
if (Build.VERSION.SDK_INT < 24) {
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
} else {
intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri pdfURI = FileProvider.getUriForFile(GalleryPdfActivity.this, getApplicationContext()
.getPackageName
() +
".provider", file);
intent.putExtra(Intent.EXTRA_STREAM, pdfURI);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.setType("application/pdf");
}
try {
if (intent.resolveActivity(getPackageManager()) != null)
startActivity(intent);
else
AppUtils.toast("No Application found to open the pdf", GalleryPdfActivity.this);
} catch (Exception e) {
AppUtils.toast(e.getMessage(), GalleryPdfActivity.this);
}
The file chooser opens and I have selected Google PDF Viewer to open the app. But it returns an error "Cannot display PDF(no file received)" . I was able to open the same file in devices prior to Android N
Add FLAG_GRANT_READ_URI_PERMISSION on the Intent in your FileProvider case. Otherwise, the other app has no access to the content. See the documentation.
Add FLAG_GRANT_READ_URI_PERMISSION
Intent intent = new Intent(Intent.ACTION_VIEW)
Uri outputFileUri = FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + ".provider", file);
intent.setDataAndType(outputFileUri, "application/pdf");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Intent in = Intent.createChooser(intent, "Open File");
startActivity(in);
also add provider_paths.xml at res -> xml folder
and need to add below code at manifests
<application>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true"
tools:replace="android:authorities">
<meta-data
tools:replace="android:resource"
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>
</application>

How to share pdf and text through whatsapp in 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

Open Image with intent from internal storage

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)

Categories

Resources