can someone help me how to send an image to another application in android?
I want to send an image to be used as wallpaper, BBM display picture, and other applications that can use it (like WhatsApp, contacts, etc.)
I use this code, but it can only be used for sending text and not images as I want
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(sendIntent);
Then I tried to use this code to set the wallpaper
public void setAsWallpaper(Bitmap bitmap) {
try {
WallpaperManager wm = WallpaperManager.getInstance(_context);
wm.setBitmap(bitmap);
//disinimas
Toast.makeText(_context,
_context.getString(R.string.toast_wallpaper_set),
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(_context,
_context.getString(R.string.toast_wallpaper_set_failed),
Toast.LENGTH_SHORT).show();
}
}
the problem with the code, bitmap images directly applied as wallpaper. I wanted like sending text above, the user can choose to use another application. So I want a bitmap image that can later be used for wallpaper, BBM display picture, or other applications that support it
bitmap variable already contains the image that I want to, the images obtained from the internet with this code:
Bitmap bitmap = ((BitmapDrawable) fullImageView.getDrawable())
.getBitmap();
I use this code and its work, but give me a message BBM: File not found, WhatsApp: File is not an image:
Bitmap icon = bitmap;
Intent share = new Intent(Intent.ACTION_ATTACH_DATA);
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"));
Thanks for your help Antrromet, finally I solved my problem with the following code:
Bitmap icon = bitmap;
// Intent share = new Intent(Intent.ACTION_SEND);
// share.setType("image/*");
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "title");
values.put(Images.Media.MIME_TYPE, "image/*");
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());
}
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setDataAndType(uri, "image/*");
intent.putExtra("mimeType", "image/*");
this.startActivity(Intent.createChooser(intent, "Set as:"));
Now the image can be used as Wallpaper, BBM profile picture, WA display Picture, Coontact display picture, etc. Thanks
Did you try using the following code? It is use to send binary data to other apps.
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage);
shareIntent.setType("image/jpeg");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)));
Or if you dont have the URI with you but have the Bitmap instead, then try using the code as given here.
UPDATE:
Setting wallpaper and profile picture for BBM are totally different things and there is no common intent for them. For setting the wallpaper, you can try the following as given here.
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setDataAndType(uri, "image/jpeg");
intent.putExtra("mimeType", "image/jpeg");
this.startActivity(Intent.createChooser(intent, "Set as:"));
For BBM, the APIs are not open for changing the user image. So you cannot do that through your app.
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"));
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.setType("image/*");
Uri uri = Uri.parse(pathToImage);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
return shareIntent;
i was used above code for sharing image on social sites.when i posting image on facebook only text is posted and image is not coming.how can we get the image and pathtoimage is string variable i am getting sever image path and stored in string variable.but it is not working.please give any solutions for my above question.?
Try this
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"));
Refer more links
http://android-developers.blogspot.in/2012/02/share-with-intents.html
Android Share Via Dialog
Image post into facebook wall from android sdcard
This is the solution I came up with:
This function allows you to share to instagram, facebook or any other app if you know the package name. If the app is not installed it redirects to the Play Store. If you send "others" as parameters, you will display a list of apps that also support image sharing.
shareImageIntent(mActivity,"image/*", "/storage/emulated/0/Pictures/Instagram/IMG_20150120_095603.jpg", "Instagram Sharing test. #Josh","com.instagram.android"); // parameters - for facebook: "com.facebook.katana" , to display list of other apps you can share to: "others"
public void shareImageIntent(Activity a,String type, String mediaPath, String caption, String app){
Intent intent = mContext.getPackageManager().getLaunchIntentForPackage(app);
if ((intent != null)||(app.equals("others"))){
// Create the new Intent using the 'Send' action.
Intent share = new Intent(Intent.ACTION_SEND);
if(!app.equals("others"))
share.setPackage(app);
// Set the MIME type
share.setType(type);
// Create the URI from the media
File media = new File(mediaPath);
Uri uri = Uri.fromFile(media);
// Add the URI and the caption to the Intent.
share.putExtra(Intent.EXTRA_STREAM, uri);
share.putExtra(Intent.EXTRA_TEXT, caption);
// Broadcast the Intent.
//startActivity(Intent.createChooser(share, "Share to"));
a.startActivity(share);
}
else{
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//intent.setData(Uri.parse("market://details?id="+"com.instagram.android"));
intent.setData(Uri.parse("market://details?id="+app));
a.startActivity(intent);
}
}
You can not use Intent to post to Facebook. They have specifically blocked this. You have to either use their SDK or copy it to the clipboard and have the user paste it after the facebook interface opens. I am having this same problem.
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"));
}