share image with URL android share intent - android

I need to know if it is possible to share an image using only its url with a share intent. Here is my code.
Intent imageIntent = new Intent(Intent.ACTION_SEND);
Uri imageUri = Uri.parse("http://eofdreams.com/data_images/dreams/face/face-03.jpg");
imageIntent.setType("image/*");
imageIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(imageIntent);
So far its not working and I haven't found any helpful answers online. I would like to do this using the share intent and without downloading the image.

You can share image using share intent, but you've to decode image to a localized Bitmap
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Hey view/download this image");
String path = Images.Media.insertImage(getContentResolver(), loadedImage, "", null);
Uri screenshotUri = Uri.parse(path);
intent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
intent.setType("image/*");
startActivity(Intent.createChooser(intent, "Share image via..."));
loadedImage is the loaded bitmap from http://eofdreams.com/data_images/dreams/face/face-03.jpg

See here HERE
final ImageView imgview= (ImageView)findViewById(R.id.feedImage1);
Uri bmpUri = getLocalBitmapUri(imgview);
if (bmpUri != null) {
// Construct a ShareIntent with link to image
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
// Launch sharing dialog for image
startActivity(Intent.createChooser(shareIntent, "Share Image"));
} else {
// ...sharing failed, handle error
}
then add this to your activity :
public Uri getLocalBitmapUri(ImageView imageView) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable){
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}

I've tried several methods, however non of them worked for me and the parts of the operations were unclear, so here is what I use for sharing image or video type content in case having the absolute path of the data.
In android manifest.xml add the following lines:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
//Other codes
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>
//Other codes
</application>
In the resource directory res, make a new folder called xml. Place a new file into it with the same name you used in the manifest.xml at the meta-data part, in this case provider_paths.xml:
android:resource="#xml/provider_paths"
Place the following in it:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="external_files"
path="." />
<root-path
name="external_files"
path="/storage/"/>
</paths>
In the activity you wish to use the share function, place the following code, where path is a string variable containing the absolute path of the content, and "com.example.fileprovider", the author value of Fileprovider is based on one of the line of the fresh xml file created above like this:
android:authorities="com.example.fileprovider"
File file = new File(path);
//Checking if the file exists
if(file.exists()) {
//Creating the Uri for the file using the provider we just created
Uri contentUri =
FileProvider.getUriForFile(Gallery.this,"com.example.fileprovider", file);
//Creating the share intent
Intent S = new Intent(Intent.ACTION_SEND);
//Allowing different types to be shared
S.setType("*/*");
S.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//Providing the uri to the intent
S.putExtra(Intent.EXTRA_STREAM, contentUri);
//Starting the intent, can choose from apps which are listening for the
//content type
startActivity(Intent.createChooser(S, "Share content using"));
}
else{
Toast.makeText(getApplicationContext(),path + " does not
exist",Toast.LENGTH_SHORT).show();
}
With this it is easy to share content from the device with the path of it.
The authorities and resource values are crucial in manifest.xml. One can change them of course, but then make sure to modify them at all occurances.
Resources:
Android Share Intent Image Sharing not working Except WhatsApp
https://www.geeksforgeeks.org/how-to-share-image-from-url-with-intent-in-android/
https://developer.android.com/training/sharing/send

convert url to string format
Intent imageIntent = new Intent(Intent.ACTION_SEND);
Uri imageUri = Uri.parse("http://eofdreams.com/data_images/dreams/face/face-03.jpg");
imageIntent.setType("image/*");
imageIntent.putExtra(Intent.EXTRA_STREAM, String.valueOf(imageUri));
startActivity(imageIntent);

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT,"http://eofdreams.com/data_images/dreams/face/face-03.jpg");
startActivity(Intent.createChooser(intent, "Share Image"));

Related

Open image in gallery with Android Nougat

I want to open a saved image in gallery on Android Nougat but what I get is a black gallery page with message "Can't load the photo".
That's my code:
Manifest
<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>
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>
Path generated in DrawView
public static boolean save(Bitmap bitmap){
Date now = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy'_'HH:mm");
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + "Crash");
if (!folder.exists()) {
folder.mkdirs();
}
FileOutputStream fos = null;
try {
lastImagePath = new File(Environment.getExternalStorageDirectory().toString() + "/Crash/" + simpleDateFormat.format(now) + ".jpg");
fos = new FileOutputStream(lastImagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
fos = null;
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {}
}
}
}
Open Image Listener
private class OpenImageListener implements View.OnClickListener{
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.N){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + DrawView.getLastImagePath().getAbsolutePath()), "image/*");
startActivity(intent);
} else {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri photoUri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".provider", DrawView.getLastImagePath());
intent.setData(photoUri);
startActivity(intent);
}
}
}
Maybe I generate a wrong path for the image, but with old version it works (I tried on Marshmallow and works great).
Can someone help me? Thanks.
In your else block in onClick(), after calling setData() on your Intent to set the Uri, call addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) on the Intent.
As it stands, the other app has no rights to work with the content identified by the Uri. Adding FLAG_GRANT_READ_URI_PERMISSION does this.
This is covered in the FileProvider documentation, along with modern books on Android app development.
I do expire the same issue with almost all apps I tried, my code is the same as yours and as far as the google docs say it looks to be correct...
The only "solution" I can offer you is to compile against version 23(https://source.android.com/source/build-numbers.html) to avoid the forced strict mode for file URIs.
Of course you also have to downgrade your Android support libs in case you are using them.
If someone has a better idea please share...
To view image from mobile emulated gallery is no more difficult but in nougat is quite different i have run time image created and wants to see that image its failed many times but finally its run with this code
1.after a long struggle i write this code , dont forget to add, fil provider in mainfest file as you may know .
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());
String type = map.getMimeTypeFromExtension(ext);
if (type == null)
type = "*/*";
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// only for gingerbread and newer versions
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri photoUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
intent.setDataAndType(photoUri, type);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION|Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(intent);
}
else{
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.fromFile(file);
intent.setDataAndType(data, type);
context.startActivity(intent);
}

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

How to attach a Bitmap when launching ACTION_SEND intent

I have this code:
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
startActivity(intent);
Which will successfully launch a Messaging App on Android.
But how can I attach a Bitmap object when launching the intent?
I have read http://developer.android.com/reference/Android/content/Intent.html,
the closet thing to what I need is EXTRA_STREAM, like this:
intent2.putExtra(Intent.EXTRA_STREAM, _uri);
But my case, I have a reference of Bitmap object, not an URI of a Bitmap.
Please tell me what to do to attach a Bitmap object?
String pathofBmp = Images.Media.insertImage(getContentResolver(), bitmap,"title", null);
Uri bmpUri = Uri.parse(pathofBmp);
final Intent emailIntent1 = new Intent( android.content.Intent.ACTION_SEND);
emailIntent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
emailIntent1.putExtra(Intent.EXTRA_STREAM, bmpUri);
emailIntent1.setType("image/png");
Where bitmap is your bitmap object which must be store in SD Card. and then use that Uri for shareimage.
You must first save the bitmap to a file. you can save it to the app's cache
private void shareBitmap (Bitmap bitmap,String fileName) {
try {
File file = new File(getContext().getCacheDir(), fileName + ".png");
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
file.setReadable(true, false);
final Intent intent = new Intent( android.content.Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
intent.setType("image/png");
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
Try this it may help you:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
yourbitmapimagename.compress(CompressFormat.PNG, 0, bos);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_STREAM, bos.toByteArray());
startActivity(intent);
#Gil Sh's answer is a great starting point. However, at least for newer Android versions (API >=24), it doesn't work out of the box. It will throw an
Exception:
android.os.FileUriExposedException: file.png exposed beyond app
through ClipData.Item.getUri()
To get around that, you need to use a FileProvider. There is a good answer in a different thread showcasing this.
However, take care if you used the internal cache (i.e. via getContext().getCacheDir()) to store the image as suggested in #Gil Sh's answer. Instead of this:
Then you need to add a file named filepaths.xml to your
app/src/main/res/xml directory with the following contents:
<paths>
<external-files-path name="Pictures" path="Pictures" />
</paths>
Use this:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<cache-path name="cache" path="."/>
</paths>
The nice thing about using the cache folder is that you won't spam the users Gallery or other folders with the images. Also, you won't need additional Permissions for your App.
String cc=trlink.toString();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT,cc);
startActivity(Intent.createChooser(share,"Share Text"));

How to use "Share image using" sharing Intent to share images in android?

I have an image galley app; in that app I placed all the images into the drawable-hdpi folder. I call images in my activity like this:
private Integer[] imageIDs = {
R.drawable.wall1, R.drawable.wall2,
R.drawable.wall3, R.drawable.wall4,
R.drawable.wall5, R.drawable.wall6,
R.drawable.wall7, R.drawable.wall8,
R.drawable.wall9, R.drawable.wall10
};
How do I share these images using sharing Intent? I put sharing code like this:
Button shareButton = (Button) findViewById(R.id.share_button);
shareButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse(Images.Media.EXTERNAL_CONTENT_URI + "/" + imageIDs);
sharingIntent.setType("image/jpeg");
sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(sharingIntent, "Share image using"));
}
});
And I have a sharing button also; when I click on the share button, the Sharing box is opening, but when I click any service, mostly it's crashing or some services say: "unable to open image". How can I fix this or is there any other format code to share images?
I tried using the code below, but it's not working.
Button shareButton = (Button) findViewById(R.id.share_button);
shareButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse("android.resource://com.android.test/*");
try {
InputStream stream = getContentResolver().openInputStream(screenshotUri);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sharingIntent.setType("image/jpeg");
sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(sharingIntent, "Share image using"));
}
});
How do I share my images from the drawable-hdpi folder?
Bitmap icon = mBitmap;
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/temporary_file.jpg"));
startActivity(Intent.createChooser(share, "Share Image"));
The solution proposed from superM worked for me for a long time, but lately I tested it on 4.2 (HTC One) and it stopped working there. I am aware that this is a workaround, but it was the only one which worked for me with all devices and versions.
According to the documentation, developers are asked to "use the system MediaStore" to send binary content. This, however, has the (dis-)advantage, that the media content will be saved permanently on the device.
If this is an option for you, you might want to grant permission WRITE_EXTERNAL_STORAGE and use the system-wide MediaStore.
Bitmap icon = mBitmap;
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "title");
values.put(Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI,
values);
OutputStream outstream;
try {
outstream = getContentResolver().openOutputStream(uri);
icon.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
outstream.close();
} catch (Exception e) {
System.err.println(e.toString());
}
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share Image"));
First add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
using Bitmap from resources
Bitmap b =BitmapFactory.decodeResource(getResources(),R.drawable.userimage);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), b, "Title", null);
Uri imageUri = Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(share, "Select"));
Tested via bluetooth and other messengers
I found the easiest way to do this is by using the MediaStore to temporarily store the image that you want to share:
Drawable mDrawable = mImageView.getDrawable();
Bitmap mBitmap = ((BitmapDrawable) mDrawable).getBitmap();
String path = MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "Image Description", null);
Uri uri = Uri.parse(path);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share Image"));
From: Sharing Content With Intents
Simple and Easiest code you can use it to share image from gallery.
String image_path;
File file = new File(image_path);
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent .setType("image/*");
intent .putExtra(Intent.EXTRA_STREAM, uri);
context.startActivity(intent );
How to share image in android progamatically , Sometimes you wants to take a snapshot of your view and then like to share it
so follow these steps: 1.Add permission to mainfest file
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2.Very First take a screenshot of your view , for example it is
Imageview, Textview, Framelayout,LinearLayout etc
For example you have an image view to take screenshot
call this method in oncreate()
ImageView image= (ImageView)findViewById(R.id.iv_answer_circle);
///take a creenshot
screenShot(image);
after taking screenshot call share image method either on button
click or where you wants
shareBitmap(screenShot(image),"myimage");
After on create method define these two method ##
public Bitmap screenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
//////// this method share your image
private void shareBitmap (Bitmap bitmap,String fileName) {
try {
File file = new File(getContext().getCacheDir(), fileName + ".png");
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
file.setReadable(true, false);
final Intent intent = new Intent( android.content.Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
intent.setType("image/png");
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
Here is a solution that worked for me. One gotcha is you need to store the images in a shared or non app private location (http://developer.android.com/guide/topics/data/data-storage.html#InternalCache)
Many suggestions say to store in the Apps "private" cache location but this of course is not accessable via other external applications, including the generic Share File intent which is being utilised. When you try this, it will run but for example dropbox will tell you the file is no longer available.
/* STEP 1 - Save bitmap file locally using file save function below. */
localAbsoluteFilePath = saveImageLocally(bitmapImage);
/* STEP 2 - Share the non private Absolute file path to the share file intent */
if (localAbsoluteFilePath!=null && localAbsoluteFilePath!="") {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
Uri phototUri = Uri.parse(localAbsoluteFilePath);
File file = new File(phototUri.getPath());
Log.d(TAG, "file path: " +file.getPath());
if(file.exists()) {
// file create success
} else {
// file create fail
}
shareIntent.setData(phototUri);
shareIntent.setType("image/png");
shareIntent.putExtra(Intent.EXTRA_STREAM, phototUri);
activity.startActivityForResult(Intent.createChooser(shareIntent, "Share Via"), Navigator.REQUEST_SHARE_ACTION);
}
/* SAVE IMAGE FUNCTION */
private String saveImageLocally(Bitmap _bitmap) {
File outputDir = Utils.getAlbumStorageDir(Environment.DIRECTORY_DOWNLOADS);
File outputFile = null;
try {
outputFile = File.createTempFile("tmp", ".png", outputDir);
} catch (IOException e1) {
// handle exception
}
try {
FileOutputStream out = new FileOutputStream(outputFile);
_bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
} catch (Exception e) {
// handle exception
}
return outputFile.getAbsolutePath();
}
/* STEP 3 - Handle Share File Intent result. Need to remote temporary file etc. */
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// deal with this with whatever constant you use. i have a navigator object to handle my navigation so it also holds all mys constants for intents
if (requestCode== Navigator.REQUEST_SHARE_ACTION) {
// delete temp file
File file = new File (localAbsoluteFilePath);
file.delete();
Toaster toast = new Toaster(activity);
toast.popBurntToast("Successfully shared");
}
}
I hope that helps someone.
Thanks all, I tried the few of the options given, but those seems not to work for the latest android releases, so adding the modified steps which work for the latest android releases. these are based on few of the answers above but with modifications & the solution is based on the use of File Provider :
Step:1
Add Following code in Manifest File:
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_provider_paths" />
</provider>
step:2
Create an XML File in res > xml
Create file_provider_paths file inside xml.
Note that this is the file which we include in the android:resource in the previous step.
Write following codes inside the file_provider_paths:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<cache-path name="cache" path="/" />
<files-path name="files" path="/" />
</paths>
Step:3
After that go to your button Click:
Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bitmap bit = BitmapFactory.decodeResource(context.getResources(), R.drawable.filename);
File filesDir = context.getApplicationContext().getFilesDir();
File imageFile = new File(filesDir, "birds.png");
OutputStream os;
try {
os = new FileOutputStream(imageFile);
bit.compress(Bitmap.CompressFormat.PNG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
}
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri imageUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, imageFile);
intent.putExtra(Intent.EXTRA_STREAM, imageUri);
intent.setType("image/*");
context.startActivity(intent);
}
});
For More detailed explanation Visit https://droidlytics.wordpress.com/2020/08/04/use-fileprovider-to-share-image-from-recyclerview/
I was tired in Searching different options for sharing view or image from my application to other application . And finally i got the solution.
Step 1 :
Share Intent handling Block. This will Pop Up your window with list of Applications in you phone
public void share_bitMap_to_Apps() {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("image/*");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
/*compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();*/
i.putExtra(Intent.EXTRA_STREAM, getImageUri(mContext, getBitmapFromView(relative_me_other)));
try {
startActivity(Intent.createChooser(i, "My Profile ..."));
} catch (android.content.ActivityNotFoundException ex) {
ex.printStackTrace();
}
}
Step 2 :
Converting your view to BItmap
public static Bitmap getBitmapFromView(View view) {
//Define a bitmap with the same size as the view
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
//Bind a canvas to it
Canvas canvas = new Canvas(returnedBitmap);
//Get the view's background
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
//has background drawable, then draw it on the canvas
bgDrawable.draw(canvas);
else
//does not have background drawable, then draw white background on the canvas
canvas.drawColor(Color.WHITE);
// draw the view on the canvas
view.draw(canvas);
//return the bitmap
return returnedBitmap;
}
Step 3 :
To get The URI from Bitmap Image
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
I just had the same problem.
Here is an answer that doesn't use any explicit file writing in your main code (letting the api taking care of it for you).
Drawable mDrawable = myImageView1.getDrawable();
Bitmap mBitmap = ((BitmapDrawable)mDrawable).getBitmap();
String path = MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "Image I want to share", null);
Uri uri = Uri.parse(path);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share Image"));
This is the path... you just need to add your image IDs in a Drawable object.
In my case (code above), the drawable was extracted from an ImageView.
SuperM answer worked for me but with Uri.fromFile() instead of Uri.parse().
With Uri.parse(), it worked only with Whatsapp.
This is my code:
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(mFile));
Output of Uri.parse():
/storage/emulated/0/Android/data/application_package/Files/17072015_0927.jpg
Output of Uri.fromFile:
file:///storage/emulated/0/Android/data/application_package/Files/17072015_0927.jpg
ref :- http://developer.android.com/training/sharing/send.html#send-multiple-content
ArrayList<Uri> imageUris = new ArrayList<Uri>();
imageUris.add(imageUri1); // Add your image URIs here
imageUris.add(imageUri2);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share images to.."));
All the Above solution doesnot work for me in Android Api 26 & 27 (Oreo), was gettting Error: exposed beyond app through ClipData.Item.getUri. The solution that fits in my situation was
get path uri using FileProvider.getUriForFile(Context,packagename,File) as
void shareImage() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(this,getPackageName(),deleteFilePath));
startActivity(Intent.createChooser(intent,"Share with..."));
}
Define a <provider> in your Manifest.xml as
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.stickerapplication"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths">
</meta-data>
</provider>
And the last step is to define resource file for your directorys
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="." />
</paths>
*Note this solution is for `external storage` `uri`
A perfect solution for share text and Image via Intent is :
On your share button click :
Bitmap image;
shareimagebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
URL url = null;
try {
url = new URL("https://firebasestorage.googleapis.com/v0/b/fir-notificationdemo-dbefb.appspot.com/o/abc_text_select_handle_middle_mtrl_light.png?alt=media&token=c624ab1b-f840-479e-9e0d-6fe8142478e8");
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
shareBitmap(image);
}
});
Then Create shareBitmap(image) method.
private void shareBitmap(Bitmap bitmap) {
final String shareText = getString(R.string.share_text) + " "
+ getString(R.string.app_name) + " developed by "
+ "https://play.google.com/store/apps/details?id=" + getPackageName() + ": \n\n";
try {
File file = new File(this.getExternalCacheDir(), "share.png");
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
file.setReadable(true, false);
final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_TEXT, shareText);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
intent.setType("image/png");
startActivity(Intent.createChooser(intent, "Share image via"));
} catch (Exception e) {
e.printStackTrace();
}
}
And then just test It..!!
With implementation of stricter security policies, exposing uri outside of app throws an error and application crashes.
#Ali Tamoor's answer explains using File Providers, this is the recommended way.
For more details see - https://developer.android.com/training/secure-file-sharing/setup-sharing
Also you need to include androidx core library to your project.
implementation "androidx.core:core:1.2.0"
Of course this is bit bulky library and need it just for sharing files -- if there is a better way please let me know.
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Log.d(TAG, "Permission granted");
} else {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
100);
}
fab.setOnClickListener(v -> {
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.refer_pic);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(requireActivity().getContentResolver(),
b, "Title", null);
Uri imageUri = Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
share.putExtra(Intent.EXTRA_TEXT, "Here is text");
startActivity(Intent.createChooser(share, "Share via"));
});
Strring temp="facebook",temp="whatsapp",temp="instagram",temp="googleplus",temp="share";
if(temp.equals("facebook"))
{
Intent intent = getPackageManager().getLaunchIntentForPackage("com.facebook.katana");
if (intent != null) {
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/png");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + "/sdcard/folder name/abc.png"));
shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.setPackage("com.facebook.katana");
startActivity(shareIntent);
}
else
{
Toast.makeText(MainActivity.this, "Facebook require..!!", Toast.LENGTH_SHORT).show();
}
}
if(temp.equals("whatsapp"))
{
try {
File filePath = new File("/sdcard/folder name/abc.png");
final ComponentName name = new ComponentName("com.whatsapp", "com.whatsapp.ContactPicker");
Intent oShareIntent = new Intent();
oShareIntent.setComponent(name);
oShareIntent.setType("text/plain");
oShareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Website : www.google.com");
oShareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(filePath));
oShareIntent.setType("image/jpeg");
oShareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
MainActivity.this.startActivity(oShareIntent);
} catch (Exception e) {
Toast.makeText(MainActivity.this, "WhatsApp require..!!", Toast.LENGTH_SHORT).show();
}
}
if(temp.equals("instagram"))
{
Intent intent = getPackageManager().getLaunchIntentForPackage("com.instagram.android");
if (intent != null)
{
File filePath =new File("/sdcard/folder name/"abc.png");
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + "/sdcard/Chitranagari/abc.png"));
shareIntent.setPackage("com.instagram.android");
startActivity(shareIntent);
}
else
{
Toast.makeText(MainActivity.this, "Instagram require..!!", Toast.LENGTH_SHORT).show();
}
}
if(temp.equals("googleplus"))
{
try
{
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
String strDate = sdf.format(c.getTime());
Intent shareIntent = ShareCompat.IntentBuilder.from(MainActivity.this).getIntent();
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Website : www.google.com");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + "/sdcard/folder name/abc.png"));
shareIntent.setPackage("com.google.android.apps.plus");
shareIntent.setAction(Intent.ACTION_SEND);
startActivity(shareIntent);
}catch (Exception e)
{
e.printStackTrace();
Toast.makeText(MainActivity.this, "Googleplus require..!!", Toast.LENGTH_SHORT).show();
}
}
if(temp.equals("share")) {
File filePath =new File("/sdcard/folder name/abc.png"); //optional //internal storage
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "Website : www.google.com");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(filePath)); //optional//use this when you want to send an image
shareIntent.setType("image/jpeg");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "send"));
}

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