Android : Share drawable resource with other apps - android

In my activity I have an ImageView. I want ,when user click on it, a dialog opens (like intent dialogs) that show list of apps which can open image than user can choose a app and show the image with that app.
my activity code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView iv = (ImageView) findViewById(R.id.imageid);
iv.setImageResource(R.drawable.dish);
iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//here is where I want a dialog that I mentioned show
}
});
}// end onCreate()

You can't pass a bitmap to an intent.
From what I see you want to share a drawable from your resources. So first you have to convert the drawable to a bitmap. And then You have to save the bitmap to the external memory as a file and then get a uri for that file using Uri.fromFile(new File(pathToTheSavedPicture)) and pass that uri to the intent like this.
shareDrawable(this, R.drawable.dish, "myfilename");
public void shareDrawable(Context context,int resourceId,String fileName) {
try {
//convert drawable resource to bitmap
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId);
//save bitmap to app cache folder
File outputFile = new File(context.getCacheDir(), fileName + ".png");
FileOutputStream outPutStream = new FileOutputStream(outputFile);
bitmap.compress(CompressFormat.PNG, 100, outPutStream);
outPutStream.flush();
outPutStream.close();
outputFile.setReadable(true, false);
//share file
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(outputFile));
shareIntent.setType("image/png");
context.startActivity(shareIntent);
}
catch (Exception e) { Toast.makeText(context, "error", Toast.LENGTH_LONG).show();
}
}

You have to startActivity using intent of type Intent.ACTION_VIEW-
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(<your_image_uri>, "image/*");
startActivity(intent);

Create a chooser by using the following code. You can add it in the part where you say imageview.setonclicklistener().
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);

Related

How to share image of app

I have picture in drawable and I want to share that one image.
Following is my code,
btnic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.defaultpicture);
Intent ppp = new Intent("android.intent.action.SEND");
ppp.setType("image/png");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(),
b, "defaultpicture", null);
Uri uri = Uri.parse(path);
ppp.putExtras(Intent.EXTRA_STREAM, uri); **i am getting error here**
MainActivity.this.startActivity(Intent.createChooser(ppp, "Send picture"));
Toast.makeText(getApplicationContext(), "Picture Copied", Toast.LENGTH_SHORT).show();
}
});
where am i doing wrong?
Intent.EXTRA_STREAM takes value as Local path of file on storage not on resource (Not a resource ID).
So you need to first save the image as file in storage then pass the url to sharing Intent .
First decode resource.
Bitmap b = BitmapFactory.decodeResource(res, id);
Save it to specific location on storage and use this file path as value in intent. you can save it as below or in some other way.
String path = MediaStore.Images.Media.insertImage(getContentResolver(),
b, "myFile", null);
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/jpg");
final File photoFile = new File(getFilesDir(), "yourimage.jpg");
Log.d("TAG", "onClick: "+photoFile);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(photoFile));
startActivity(Intent.createChooser(shareIntent, "Share image using"));
for more about Sharing Content with Intents

Add option to share image from Adapter

I was working on a Gallery type app. I wanted to add a share option whenever the specific image is tapped but have failed to do so.
I tried to create Intents, It did not work. What should I do?
Here is my Adapter Class code: https://gist.github.com/mukundmadhav/e63fcf7e34414b9b88458400a6d55651
(Also for testing I have saved 8 images in drawable folder)
When I use Intents it shows this error message:
Error:(51, 17) error: cannot find symbol method startActivity(Intent)
I have imported the android.content.Intent but the error still persists.
try this in adapter :
viewHolder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//here write code to share image //get clicked image bitmap and then share
Bitmap bitmap = ((BitmapDrawable)viewHolder.img.getDrawable()).getBitmap();
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("image/png");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(context.getContentResolver(), bitmap , "Title", null);
// Uri uri = Uri.parse("android.resource://your package
//name/"+R.drawable.ic_launcher);
Uri uri = Uri.parse(path);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello, This is test Sharing");
startActivity(Intent.createChooser(shareIntent, "Send your image"));
}
});

Android Intent ImageChooser Image Path

I am using Android Intent Chooser to select a photo from gallery with following code.
ivAvatar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Bir fotoğraf seçin ..."), 1);
}
});
After selection using the path I fill the imageview with following code :
Uri selectedImageUri = data.getData();
imagepath = ImagePathUtil.getPath(getApplicationContext(), selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
ivAvatar.setImageBitmap(bitmap);
selectedU = selectedImageUri;
File f = new File(String.valueOf(selectedU));
if(f.exists())
{
int i = 1;
}
Image can be viewed without any problems, but the File object I create afterwards File 's exists() method always return false.
It is returning false because the file will be null. Please look at the below post for more details on how to get the real path from URI.
URI from Intent.ACTION_GET_CONTENT into File

How to use bitmap to send to another app

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.

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

Categories

Resources