How to properly create an Intent to refer like Tez? - android

In my app i have to add an intent to share my app. I looked through Tez, which shares the app icon along with a text which contains a hyperlink. How to achieve this?

you can try this one..
Uri uri = Uri.fromFile(imageFile);
Intent intent1 = new Intent();
intent1.setAction(Intent.ACTION_SEND);
intent1.setType("image/*");
intent1.putExtra(android.content.Intent.EXTRA_SUBJECT, "App Name");
intent1.putExtra(Intent.EXTRA_TEXT, "Download the app from google play store now - "+ APP_STORE_URL);
intent1.putExtra(Intent.EXTRA_STREAM, uri);
try {
startActivity(Intent.createChooser(intent1, "Share"));
} catch (ActivityNotFoundException e) {
Toast.makeText(getContext(), "please try again", Toast.LENGTH_SHORT).show();
}
this will works : put image file and text box in share intent

private void prepareShareIntent(Bitmap bmp) {
Uri bmpUri = getLocalBitmapUri(bmp); // see previous remote images section
// Construct share intent as described above based on bitmap
Intent shareIntent = new Intent();
shareIntent = new Intent();
shareIntent.setPackage("com.whatsapp");
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.share_app) );
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Share Opportunity"));
}
private Uri getLocalBitmapUri(Bitmap bmp) {
Uri bmpUri = null;
File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".png");
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
bmpUri = Uri.fromFile(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bmpUri;
}

It look like you want to create an referrer links for which try using this firebase service.Once you have got your referrer URL ready.Create an intent as follow to share it.
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, subjectText);
shareIntent.putExtra(Intent.EXTRA_HTML_TEXT, "Hey!Checkout this app "+ APP_STORE_URL);
shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(shareIntent, "Invite Friends"));
**Note:**If you are using dynamic links you can add your app icon in the social meta tags param

Try this
Uri imageUri = Uri.parse("android.resource://" + getPackageName() + "/drawable/" + "ic_launcher");
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello" + REFERRAL_URL);
shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
shareIntent.setType("image/jpeg");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "send"));`

Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
/**This is the image to share**/
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "title");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = getContentResolver().insert(MediaStore.Images.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);
share.putExtra(Intent.EXTRA_TEXT, "YOUR_BODY_TEXT_HERE");
startActivity(Intent.createChooser(share, "Share Image"));
I've tested the above code, it works as per your requirement.
PS: You need to have WRITE_EXTERNAL_STORAGE permission. Be sure to include it and handle it according to SDK's.

This code will share both the files together
ArrayList<Uri> myFilesUriList = new ArrayList<>();
myFilesUriList.add(); // add your image path as uri
myFilesUriList.add(); // add your text file path as uri
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.setType("image/*");
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, myFilesUriList);
startActivity(intent);
This code will share both the files Separately
First share the file then on Activity Result, share text Separately
ArrayList<Uri> uriArrayList = new ArrayList<>();
uriArrayList.add(); // add your image path as uri
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.setType("image/*");
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uriArrayList);
startActivityForResult(intent, 156);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 156) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/*");
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, ""); //"Subject here"
sharingIntent.putExtra(Intent.EXTRA_TEXT, "shareBody ");
sharingIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(Intent.createChooser(sharingIntent, "Share text via.."));
}
}

It's URL Meta Data. These meta data is returned as response from server.
<meta property="og:site_name" content="San Roque 2014 Pollos">
<meta property="og:title" content="San Roque 2014 Pollos" />
<meta property="og:description" content="Programa de fiestas" />
<meta property="og:image" itemprop="image" content="http://pollosweb.wesped.es/programa_pollos/play.png">
<meta property="og:type" content="website" />
<meta property="og:updated_time" content="1440432930" />
Showing Thumbnail for link in WhatsApp || og:image meta-tag doesn't work

Step 1 - Read the image which you want to share
Step 2 - Store that image in your external storage
Step 3 - share via intent
// Extract Bitmap from ImageView drawable
Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.launcher); // your image
if (drawable instanceof BitmapDrawable) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
// Store image to default external storage directory
Uri bitmapUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bitmapUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
if (bitmapUri != null) {
Intent shareIntent = new Intent();
shareIntent.putExtra(Intent.EXTRA_TEXT, "I am inviting you to join our app. A simple and secure app developed by us. https://www.google.co.in/");
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bitmapUri);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share my app"));
}
}
Note - Add WRITE_EXTERNAL_STORAGE permission in your manifest. Ask runtime permission on Android 6.0 and higher.

You might be looking for deep linking to your app
https://developer.android.com/training/app-links/index.html
https://developer.android.com/training/app-links/deep-linking.html
Or if you want links to your app across platforms you can check out Firebase dynamic links
https://firebase.google.com/docs/dynamic-links/

Copy this code into your toolbar/menu
try {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "Your Subject");
String text = "\nYour description";
text = text + "https://play.google.com/store/apps/details?id=apppackagename \n\n";
i.putExtra(Intent.EXTRA_TEXT, text);
startActivity(Intent.createChooser(i, "Choose "));
}
catch(Exception e) {
//e.toString();
}

Try this code:
int applicationNameId = context.getApplicationInfo().labelRes;
final String appPackageName = context.getPackageName();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, activity.getString(applicationNameId));
String text = "Install this cool application: ";
String link = "https://play.google.com/store/apps/details?id=" + appPackageName;
i.putExtra(Intent.EXTRA_TEXT, text + " " + link);
startActivity(Intent.createChooser(i, "Share link:"));
if you want to share your other apps from your dev. account you can do something like this
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://play.google.com/store/apps/developer?
id=Your_Publisher_Name"));
startActivity(intent);

Related

Sharing Image using intent in watsApp is not working

I am sharing two URI image resource which from mipmap and ACTION_GET_CONTENT used URI.
public void shareUsingIntent() {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("image/*");
i.putExtra(Intent.EXTRA_STREAM, getUri());
startActivity(Intent.createChooser(i, "Share Image"));
}
public Uri getUri() {
if (selectedImageUri != null) {
return selectedImageUri;
} else {
return Uri.parse("android.resource://" + getPackageName() + "/" + R.mipmap.ic_launcher);
}
}
It was worked in ACTION_GET_CONTENT used URI but mipmap resource was not working in some application like Facebook and watsapp. I read from some stack answer that Image must be add in Extenrnal storage. Its not working for this URI.
Uri.parse("android.resource://" + getPackageName() + "/" + R.mipmap.ic_launcher
in what's app and Facebook and why it was working in other app like default messing app, Twitter etc.?
Try this function:
// if targetSDK >= 23, please check for runtime permission: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Also add the same permission to your Manifest file.
private void shareViaWhatsApp() {
Uri imageUri = null;
try {
imageUri = Uri.parse(MediaStore.Images.Media.insertImage(this.getContentResolver(),
BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher), null, null)); //You may need to check for permission for this.
} catch (NullPointerException e) {
}
final Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
emailIntent.putExtra(Intent.EXTRA_TEXT, "Text to share");
emailIntent.putExtra(Intent.EXTRA_STREAM, imageUri); //............Pass Image URI here.........
emailIntent.setType("image/*");
emailIntent.setPackage("com.whatsapp");
startActivity(Intent.createChooser(emailIntent, "Share..."));
}
You can try this:
boolean isWhatsappInstalled = whatsappInstalledOrNot("com.whatsapp");
if (isWhatsappInstalled) {
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,"http://play.google.com/store/apps/details?id=" + getPackageName());
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), getBitMap(), "I am Happy", "Share happy !")));
sendIntent.setType("image/png");
sendIntent.setPackage("com.whatsapp");
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(sendIntent);
} else {
Toast.makeText(getApplicationContext(), "WhatsApp not Installed", Toast.LENGTH_SHORT).show();
Uri uri = Uri.parse("market://details?id=com.whatsapp");
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
startActivity(goToMarket);
}
where getBitMap() is function in which get the image bitmap which you want to share.
Use Below Code for every app in you can share image, like whats app, hike or mail and many other
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("image/png");
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/"+R.mipmap.ic_launcher);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello, This is test Sharing");
startActivity(Intent.createChooser(shareIntent, "Send your image"));

Android Share Intent Image Sharing not working

I am new to Android and is having problem sharing image through share intent. I have googled alot, tried various things but still could not find the solution.
My code is:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_STREAM,uri);
this.startActivityForResult(Intent.createChooser(shareIntent,"Share with"),12);
I have checked the uri, the file saved is a bitmap and its returning file. But the image which shows during sharing is not valid. Gmail says it could not attach the attachment, messages app could not load the image.
Text sharing is working fine.
Basically I am writing a plugin for Unity. Here is my code on Unity Side:
string destination = Path.Combine(Application.persistentDataPath,"sharingImage" + ".png");
if (!File.Exists(destination)) {
print("creating new file");
File.Create(destination);
}
File.WriteAllBytes(destination, bytes);
print("destination= "+destination);
AndroidJavaClass uriClass = new AndroidJavaClass("android.net.Uri");
AndroidJavaObject uriObject = uriClass.CallStatic<AndroidJavaObject>("parse","file://" + destination);
using (AndroidJavaClass pluginClass = new AndroidJavaClass("com.kashiftasneem.sharelib.ShareController")) {
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
pluginClass.CallStatic("Share",message,uriObject,jo,gameObject.name,destination);
}
I am logging destination and uri, they are:
destination=
/data/data/com.kashiftasneem.shareandroidplugin2/files/sharingImage.png
uri =
file:///data/data/com.kashiftasneem.shareandroidplugin2/files/sharingImage.png
Try this code:
Bitmap bitmap = getBitmapFromView(idForSaveView);
try {
File file = new File(this.getExternalCacheDir(), "appdiam.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_STREAM, Uri.fromFile(file));
intent.setType("image/png");
startActivity(Intent.createChooser(intent, "Share image via"));
} catch (Exception e) {
e.printStackTrace();
}
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)));
It might help.

photo share intent in android

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.

Share image with Android intent

I'm trying to share an image trough a share intent like this:
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("image/png");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, application.getString(R.string.app_name));
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT,application.getString(R.string.app_share_message));
File image = new File(Uri.parse("android.resource://" + C.PROJECT_PATH + "/drawable/" + R.drawable.icon_to_share).toString());
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(image));
shareMe(sharingIntent);
The share intent fires correctly and I choose Gmail, everything runs as expected until I press send. I receive a notification "Unable to show attach", and the e-mail is sent without it...
Why?
Thanks for your time.
First, there is no guarantee that any given other app will be able to support an android:resource// Uri. You will have greater compatibility sharing a file on external storage or using a ContentProvider.
That being said, replace:
File image = new File(Uri.parse("android.resource://" + C.PROJECT_PATH + "/drawable/" + R.drawable.icon_to_share).toString());
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(image));
with:
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("android.resource://" + C.PROJECT_PATH + "/drawable/" + R.drawable.icon_to_share);
An android:resource:// is not a File, and probably you are messing up your Uri by converting to a File and then back to a Uri.
BitmapDrawable bitmapDrawable = (BitmapDrawable)ImageView.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
// Save this bitmap to a file.
File cache = getApplicationContext().getExternalCacheDir();
File sharefile = new File(cache, "toshare.png");
Log.d("share file type is", sharefile.getAbsolutePath());
try {
FileOutputStream out = new FileOutputStream(sharefile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (IOException e) {
Log.e("ERROR", String.valueOf(e.getMessage()));
}
// Now send it out to share
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM,
Uri.parse("file://" + sharefile));
startActivity(Intent.createChooser(share,
"Share Image"));
In my case I used:
Uri imageUri = Uri.parse("android.resource://com.examle.tarea/" + R.drawable.tienda_musica);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(intent, getString(R.string.action_share)));
//open a share intent chooser (Will show installed app from which i can share //images)
private void shareImage(String imagePath, String quoteByPerson, String quoteToShare)
{
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
// String imagePath = Environment.getExternalStorageDirectory() +
// "/myImage.png";
File imageFileToShare = new File(imagePath);
Uri uri = Uri.fromFile(imageFileToShare);
share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
share.putExtra(Intent.EXTRA_TEXT, "Quote of the day-:" + "\n" + quoteToShare + "\n" + quoteByPerson);
share.putExtra(android.content.Intent.EXTRA_TITLE, "Quote of the day-:");
if (imagePath.contains("android.resource://"))
{
Uri imageUri = Uri.parse(imagePath);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
} else
{
share.putExtra(Intent.EXTRA_STREAM, uri);
}
startActivity(Intent.createChooser(share, "Share inspiration via..."));
}

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