I have been struggling to send text from my app to Twitter.
The code below works to bring up a list of apps such as Bluetooth, Gmail, Facebook and Twitter, but when I select Twitter it doesn't prefill the text as I would have expected.
I know that there are issues around doing this with Facebook, but I must be doing something wrong for it to not be working with Twitter.
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "Example Text");
startActivity(Intent.createChooser(intent, "Share Text"));
I'm using this snippet on my code:
private void shareTwitter(String message) {
Intent tweetIntent = new Intent(Intent.ACTION_SEND);
tweetIntent.putExtra(Intent.EXTRA_TEXT, "This is a Test.");
tweetIntent.setType("text/plain");
PackageManager packManager = getPackageManager();
List<ResolveInfo> resolvedInfoList = packManager.queryIntentActivities(tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);
boolean resolved = false;
for (ResolveInfo resolveInfo : resolvedInfoList) {
if (resolveInfo.activityInfo.packageName.startsWith("com.twitter.android")) {
tweetIntent.setClassName(
resolveInfo.activityInfo.packageName,
resolveInfo.activityInfo.name);
resolved = true;
break;
}
}
if (resolved) {
startActivity(tweetIntent);
} else {
Intent i = new Intent();
i.putExtra(Intent.EXTRA_TEXT, message);
i.setAction(Intent.ACTION_VIEW);
i.setData(Uri.parse("https://twitter.com/intent/tweet?text=" + urlEncode(message)));
startActivity(i);
Toast.makeText(this, "Twitter app isn't found", Toast.LENGTH_LONG).show();
}
}
private String urlEncode(String s) {
try {
return URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
Log.wtf(TAG, "UTF-8 should always be supported", e);
return "";
}
}
Hope it helps.
you can simply open the URL with the text and Twitter App will do it. ;)
String url = "http://www.twitter.com/intent/tweet?url=YOURURL&text=YOURTEXT";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
and it will also open the browser to login at the tweet if twitter app is not found.
Try this, I used it and worked great
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://twitter.com/intent/tweet?text=...."));
startActivity(browserIntent);
First you have to check if the twitter app installed on the device or not then share the text on twitter:
try
{
// Check if the Twitter app is installed on the phone.
getActivity().getPackageManager().getPackageInfo("com.twitter.android", 0);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setClassName("com.twitter.android", "com.twitter.android.composer.ComposerActivity");
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "Your text");
startActivity(intent);
}
catch (Exception e)
{
Toast.makeText(getActivity(),"Twitter is not installed on this device",Toast.LENGTH_LONG).show();
}
For sharing text and image on Twitter, more controlled version of code is below, you can add more methods for sharing with WhatsApp, Facebook ... This is for official App and does not open browser if app not exists.
public class IntentShareHelper {
public static void shareOnTwitter(AppCompatActivity appCompatActivity, String textBody, Uri fileUri) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.setPackage("com.twitter.android");
intent.putExtra(Intent.EXTRA_TEXT,!TextUtils.isEmpty(textBody) ? textBody : "");
if (fileUri != null) {
intent.putExtra(Intent.EXTRA_STREAM, fileUri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setType("image/*");
}
try {
appCompatActivity.startActivity(intent);
} catch (android.content.ActivityNotFoundException ex) {
ex.printStackTrace();
showWarningDialog(appCompatActivity, appCompatActivity.getString(R.string.error_activity_not_found));
}
}
public static void shareOnWhatsapp(AppCompatActivity appCompatActivity, String textBody, Uri fileUri){...}
private static void showWarningDialog(Context context, String message) {
new AlertDialog.Builder(context)
.setMessage(message)
.setNegativeButton(context.getString(R.string.close), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setCancelable(true)
.create().show();
}
}
For getting Uri from File, use below class:
public class UtilityFile {
public static #Nullable Uri getUriFromFile(Context context, #Nullable File file) {
if (file == null)
return null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
try {
return FileProvider.getUriForFile(context, "com.my.package.fileprovider", file);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} else {
return Uri.fromFile(file);
}
}
// Returns the URI path to the Bitmap displayed in specified ImageView
public static Uri getLocalBitmapUri(Context context, ImageView imageView) {
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 {
// Use methods on Context to access package-specific directories on external storage.
// This way, you don't need to request external read/write permission.
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = getUriFromFile(context, file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
}
For writing FileProvider, use this link: https://github.com/codepath/android_guides/wiki/Sharing-Content-with-Intents
Related
I need to share both an image and some text via WhatsApp, using an Intent on Android.
Uri imageUri = Uri.parse(Filepath);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setPackage("com.whatsapp");
shareIntent.putExtra(Intent.EXTRA_TEXT, "My sample image text");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(imageUrl));
shareIntent.setType("image/png");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(shareIntent);
} catch (android.content.ActivityNotFoundException ex) {
ToastHelper.MakeShortText("Kindly install whatsapp first");
}
Iām using the code above, but it throws a 'File format not supported' error while sharing.
You can try like this
public static void shareOnWhatsapp(Context context, String str) {
Uri parse = Uri.parse(str);
Intent intent = new Intent();
intent.setAction("android.intent.action.SEND");
intent.setPackage("com.whatsapp");
String stringBuilder = context.getResources().getString(R.string.play_more_app) +
context.getPackageName();
intent.putExtra("android.intent.extra.TEXT", stringBuilder);
intent.putExtra("android.intent.extra.STREAM", parse);
intent.setType("image/*");
intent.addFlags(1);
try {
context.startActivity(intent);
} catch (Exception unused) {
setToast(context, context.getResources().getString(R.string.whatsapp_not_installed));
}
}
I used this function to share images it's working I hope it's work you too.
Edit
Add this dependency for converting URL to bitmap
implementation 'com.github.bumptech.glide:glide:4.14.2'
Use this function to get Image URI to share
private Uri getImageURI(Bitmap image) {
File imagesFolder = new File(getCacheDir(), "images");
Uri uri = null;
try {
imagesFolder.mkdirs();
File file = new File(imagesFolder, "shared_image.png");
FileOutputStream stream = new FileOutputStream(file);
image.compress(Bitmap.CompressFormat.PNG, 90, stream);
stream.flush();
stream.close();
uri = FileProvider.getUriForFile(this, getPackageName() + ".provider", file);
} catch (IOException e) {
Log.d("TAG", "IOException while trying to write file for sharing: " + e.getMessage());
}
return uri;
}
Use this function for share Image on WhatsApp
public static void shareOnWhatsapp(Context context, Uri uri) {
Intent intent = new Intent();
intent.setAction("android.intent.action.SEND");
intent.setPackage("com.whatsapp");
String stringBuilder = "Your String Or Message" +
context.getPackageName();
intent.putExtra("android.intent.extra.TEXT", stringBuilder);
intent.putExtra("android.intent.extra.STREAM", uri);
intent.setType("image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
context.startActivity(intent);
} catch (Exception unused) {
Toast.makeText(context, "whatsapp not installed", Toast.LENGTH_SHORT).show();
}
}
Uses like this
findViewById(R.id.btnShare).setOnClickListener(v -> {
Glide.with(this).asBitmap().load( /*Your URL*/ "https://drinkprime.in/images/smart_water_purifier.jpg").into(new CustomTarget<Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<? super Bitmap> transition) {
Bitmap bitmap = resource;
shareOnWhatsapp(MainActivity.this, getImageURI(bitmap));
}
#Override
public void onLoadCleared(#Nullable Drawable placeholder) {
}
});
});
It's Working now completely
here is the code through which i am sharing my image or video from an adaptor to WhatsApp it was working fine but now just the toast is shown that whats app not install is there any issue in the code am I missing something?
public void shareWhatsapp(String type, String path, String package_name) {
Uri uri = FileProvider.getUriForFile(mFragment, BuildConfig.APPLICATION_ID + ".provider", new File(path));
PackageManager pm = mFragment.getPackageManager();
try {
PackageInfo info = pm.getPackageInfo(package_name, PackageManager.GET_META_DATA);
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sharingIntent.setType(type);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
sharingIntent.setPackage(package_name);
mFragment.startActivity(Intent.createChooser(sharingIntent, "Share via"));
} catch (PackageManager.NameNotFoundException e) {
Toast.makeText(mFragment, "WhatsApp not Installed", Toast.LENGTH_SHORT)
.show();
}
}
here is the listener
holder.repostWhatsapp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ModelStatus curVideo = getItem(position);
if (curVideo.getFull_path().endsWith(".jpg")) {
shareWhatsapp("image/jpg", curVideo.getFull_path(), "com.whatsapp");
} else if (curVideo.getFull_path().endsWith(".mp4")) {
shareWhatsapp("video/mp4", curVideo.getFull_path(), "com.whatsapp");
}
}
});
use below code to share image or video to whatsapp
holder.repostWhatsapp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri uri = FileProvider.getUriForFile(PdfRendererActivity.this,
PdfRendererActivity.this.getPackageName() + ".provider", outputFile);
if (curVideo.getFull_path().endsWith(".jpg")) {
shareWhatsapp("image/jpg", uri);
} else if (curVideo.getFull_path().endsWith(".mp4")) {
shareWhatsapp("video/mp4", uri);
}
}
});
shareWhatsApp
void shareWhatsapp(String type, String uri)
{
Intent share = new Intent();
share.setAction(Intent.ACTION_SEND);
share.setType(type);
share.putExtra(Intent.EXTRA_STREAM, uri);
share.setPackage("com.whatsapp");
startActivity(share);
}
I am using this code to share an image:
File file = ImageLoader.getInstance().getDiskCache().get(imageUrl);
if (file != null && file.exists()) {
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Hello");
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType("image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(Intent.createChooser(intent, "Send"));
} else {
Toast.makeText(context, "Image cannot be shared", Toast.LENGTH_SHORT).show();
}
I used UIL to load the image previously, so mageLoader.getInstance().getDiskCache().get(imageUrl); returns the image file from disk cache.
Gmail, Hangouts, Messages, Drive etc can grab the file but on Google+, the grabbed is not gotten while Whatsapp says "This format is not supported". However if I save the file to Downloads folder and share via Gallery app, the same image is picked by both Google+ and Whatsapp.
You can try to save the file to the external cache, it's working for me. Example with Glide:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setType("image/*");
Glide.with(getContext())
.load("http://...url.here...")
.asBitmap()
.into(new SimpleTarget<Bitmap>(500, 500) {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
try {
File file = new File(getContext().getExternalCacheDir(), "file_to_share.png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
resource.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
getContext().startActivity(Intent.createChooser(sendIntent, ""));
} catch (IOException e) {
Log.e("Share", e.getMessage(), e);
} finally {
}
}
});
In case you're using Universal Image Loader, I applied the accepted answer to save the image and delete it as soon as the user returns from sharing:
private File saveImage(String imageUri, String fileName) {
File file = new File(this.getExternalCacheDir(), fileName);
InputStream sourceStream = null;
File cachedImage = ImageLoader.getInstance().getDiskCache().get(imageUri);
if (cachedImage != null && cachedImage.exists()) {
Log.d(TAG, "Cache exists");
try {
sourceStream = new FileInputStream(cachedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
Log.d(TAG, "Cache doesn't exist");
}
if (sourceStream != null) {
Log.d(TAG, "SourceStream is not null");
try {
OutputStream targetStram = new FileOutputStream(file);
try {
try {
IoUtils.copyStream(sourceStream, targetStram, null);
} catch (IOException e) {
e.printStackTrace();
}
} finally {
try {
targetStram.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
sourceStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
Log.d(TAG, "SourceStream is null");
Toast.makeText(this, "Image cannot be shared", Toast.LENGTH_SHORT).show();
}
return file;
}
private void shareImage(String imageUrl, String fileName) {
if (isSDReadableWritable()) {
file = saveImage(imageUrl, fileName);
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Hello");
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType("image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(Intent.createChooser(intent, "Send"), 20);
} else {
Toast.makeText(this, "Storage cannot be accessed", Toast.LENGTH_SHORT).show();
}
}
To delete the file just override onActivityResult and it'll be deleted immediately after sharing
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 20 && file != null) {
boolean isDelete = file.delete();
Log.d(TAG, "isDelete is " + isDelete);
}
}
I have in my app a share button and i want to share an image and a text at the same time. In GMail it works fine but in WhatsApp, only the image is sent and in Facebook the app crashes.
The code i use to share is this:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Message");
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/drawable/ford_focus_2014");
try {
InputStream stream = getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
If I use "shareIntent.setType("*/ *")" Facebook and WhatsApp crashes.
Is there some way to do this? Maybe sent two messages by separate at the same time (WhatsApp).
Thanks in advance.
Currently Whatsapp supports Image and Text sharing at the same time. (Nov 2014).
Here is an example of how to do this:
/**
* Show share dialog BOTH image and text
*/
Uri imageUri = Uri.parse(pictureFile.getAbsolutePath());
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
//Target whatsapp:
shareIntent.setPackage("com.whatsapp");
//Add text and then Image URI
shareIntent.putExtra(Intent.EXTRA_TEXT, picture_text);
shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
shareIntent.setType("image/jpeg");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(shareIntent);
} catch (android.content.ActivityNotFoundException ex) {
ToastHelper.MakeShortText("Whatsapp have not been installed.");
}
Please try the below code and hopefully it will work.
Uri imgUri = Uri.parse(pictureFile.getAbsolutePath());
Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
whatsappIntent.setType("text/plain");
whatsappIntent.setPackage("com.whatsapp");
whatsappIntent.putExtra(Intent.EXTRA_TEXT, "The text you wanted to share");
whatsappIntent.putExtra(Intent.EXTRA_STREAM, imgUri);
whatsappIntent.setType("image/jpeg");
whatsappIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
activity.startActivity(whatsappIntent);
} catch (android.content.ActivityNotFoundException ex) {
ToastHelper.MakeShortText("Whatsapp have not been installed.");
}
For sharing text and image on WhatsApp, more controlled version of code is below, you can add more methods for sharing with Twitter, Facebook ...
public class IntentShareHelper {
public static void shareOnWhatsapp(AppCompatActivity appCompatActivity, String textBody, Uri fileUri) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.setPackage("com.whatsapp");
intent.putExtra(Intent.EXTRA_TEXT,!TextUtils.isEmpty(textBody) ? textBody : "");
if (fileUri != null) {
intent.putExtra(Intent.EXTRA_STREAM, fileUri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setType("image/*");
}
try {
appCompatActivity.startActivity(intent);
} catch (android.content.ActivityNotFoundException ex) {
ex.printStackTrace();
showWarningDialog(appCompatActivity, appCompatActivity.getString(R.string.error_activity_not_found));
}
}
public static void shareOnTwitter(AppCompatActivity appCompatActivity, String textBody, Uri fileUri){...}
private static void showWarningDialog(Context context, String message) {
new AlertDialog.Builder(context)
.setMessage(message)
.setNegativeButton(context.getString(R.string.close), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setCancelable(true)
.create().show();
}
}
For getting Uri from File, use below class:
public class UtilityFile {
public static #Nullable Uri getUriFromFile(Context context, #Nullable File file) {
if (file == null)
return null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
try {
return FileProvider.getUriForFile(context, "com.my.package.fileprovider", file);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} else {
return Uri.fromFile(file);
}
}
// Returns the URI path to the Bitmap displayed in specified ImageView
public static Uri getLocalBitmapUri(Context context, ImageView imageView) {
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 {
// Use methods on Context to access package-specific directories on external storage.
// This way, you don't need to request external read/write permission.
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = getUriFromFile(context, file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
}
For writing FileProvider, use this link: https://github.com/codepath/android_guides/wiki/Sharing-Content-with-Intents
As of now, a Whatsapp Intent supports image and text:
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT,title + "\n\nLink : " + link );
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(sharePath));
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share image via:"));
The image will be as it is and EXTRA_TEXT will be shown as the caption.
try with this code
Uri imageUri = Uri.parse(Filepath);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setPackage("com.whatsapp");
shareIntent.putExtra(Intent.EXTRA_TEXT, "My sample image text");
shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
shareIntent.setType("image/jpeg");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(shareIntent);
} catch (android.content.ActivityNotFoundException ex) {
ToastHelper.MakeShortText("Kindly install whatsapp first");
}
public void shareIntentSpecificApps(String articleName, String articleContent, String imageURL) {
List<Intent> intentShareList = new ArrayList<Intent>();
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
//shareIntent.setType("image/*");
List<ResolveInfo> resolveInfoList = getPackageManager().queryIntentActivities(shareIntent, 0);
for (ResolveInfo resInfo : resolveInfoList) {
String packageName = resInfo.activityInfo.packageName;
String name = resInfo.activityInfo.name;
Log.d("System Out", "Package Name : " + packageName);
Log.d("System Out", "Name : " + name);
if (packageName.contains("com.facebook") ||
packageName.contains("com.whatsapp")) {
Intent intent = new Intent();
intent.setComponent(new ComponentName(packageName, name));
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, articleName);
intent.putExtra(Intent.EXTRA_TEXT, articleName + "\n" + articleContent);
Drawable dr = ivArticleImage.getDrawable();
Bitmap bmp = ((GlideBitmapDrawable) dr.getCurrent()).getBitmap();
intent.putExtra(Intent.EXTRA_STREAM, getLocalBitmapUri(bmp));
intent.setType("image/*");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intentShareList.add(intent);
}
}
if (intentShareList.isEmpty()) {
Toast.makeText(ArticleDetailsActivity.this, "No apps to share !", Toast.LENGTH_SHORT).show();
} else {
Intent chooserIntent = Intent.createChooser(intentShareList.remove(0), "Share Articles");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentShareList.toArray(new Parcelable[]{}));
startActivity(chooserIntent);
}
}
You can share image also I have done in my app like mentioned in above code.
My second answer for this question is: I'm pasting full code here because new developer need sometimes full code.
public class ImageSharer extends AppCompatActivity {
private ImageView imgView;
private Button shareBtn;
FirebaseStorage fs;
StorageReference sr,sr1;
String Img_name;
File dir1;
Uri uri1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.app_sharer);
imgView = (ImageView) findViewById(R.id.imgView);
shareBtn = (Button) findViewById(R.id.shareBtn);
// Initilize firebasestorage instance
fs=FirebaseStorage.getInstance();
sr=fs.getReference();
Img_name="10.jpg";
sr1=sr.child("shiva/"+Img_name);
final String Paths= Environment.getExternalStorageDirectory()+ File.separator+"The_Bhakti"+File.separator+"Data";
dir1=new File(Paths);
if(!dir1.isDirectory())
{
dir1.mkdirs();
}
sr1.getFile(new File(dir1,Img_name)).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
sr1.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
uri1= Uri.parse(uri.toString());
}
});
}
}) ;
shareBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uri1=Uri.parse(Paths+File.separator+Img_name);
Intent intent=new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
//intent.putExtra(intent.EXTRA_SUBJECT,"Insert Something new");
String data = "Hello";
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(Intent.EXTRA_TEXT,data);
intent.putExtra(Intent.EXTRA_STREAM,uri1);
intent.setPackage("com.whatsapp");
// for particular choose we will set getPackage()
/*startActivity(intent.createChooser(intent,"Share Via"));*/// this code use for universal sharing
startActivity(intent);
// end Share code
}
});
}// onCreate closer
}
Use this code for sharing on whatsapp or on another package with image and video. Here the URI is the path of image. If image in Memory then it took fast loading and if you are using url then sometimes images don't load and links gone direct.
shareBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uri1=Uri.parse(Paths+File.separator+Img_name);
Intent intent=new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
//intent.putExtra(intent.EXTRA_SUBJECT,"Insert Something new");
String data = "Hello";
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(Intent.EXTRA_TEXT,data);
intent.putExtra(Intent.EXTRA_STREAM,uri1);
intent.setPackage("com.whatsapp");
startActivity(intent);
// end Share code
}
If this code is not understandable then see the full code in my other answer.
Actually. it is possible to send image and text through WhatsApp by downloading the image to device external storage and then share the image to WhatsApp.
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Bitmap bm = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
Intent intent = new Intent(Intent.ACTION_SEND);
String share_text = "image and text";
intent.putExtra(Intent.EXTRA_TEXT, notification_share);
String path = MediaStore.Images.Media.insertImage(MainActivity.this.getContentResolver(), bm, "", null);
Uri screenshotUri = Uri.parse(path);
intent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
intent.setType("image/*");
startActivity(Intent.createChooser(intent, "Share image via..."));
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
//The above code works perfect need to show image in an imageView
This works:
<activity android:name="com.selcuksoydan.sorucevap.Main">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.SEND" />
<data android:mimeType="image/*" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
soru_image = (ImageView) soruView.findViewById(R.id.soru_image);
soru_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
v.buildDrawingCache();
Bitmap bitmap = v.getDrawingCache();
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/SoruCevap");
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception ex) {
//ignore
}
Intent waIntent = new Intent(Intent.ACTION_SEND);
waIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
waIntent.setType("image/*");
waIntent.setPackage("com.whatsapp");
waIntent.putExtra(android.content.Intent.EXTRA_STREAM, Uri.fromFile(file));
getContext().startActivity(Intent.createChooser(waIntent, "Share with"));
} catch (Exception e) {
Log.e("Error on sharing", e + " ");
Toast.makeText(getContext(), "App not Installed", Toast.LENGTH_SHORT).show();
}
This worked for me in January 2019
private void shareIntent() {
Bitmap imgBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
String imgBitmapPath = MediaStore.Images.Media.insertImage(getContentResolver(),imgBitmap,"title",null);
Uri imgBitmapUri = Uri.parse(imgBitmapPath);
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.putExtra(Intent.EXTRA_STREAM,imgBitmapUri);
shareIntent.setType("image/png");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.putExtra(Intent.EXTRA_TEXT, "My Custom Text ");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject text");
startActivity(Intent.createChooser(shareIntent, "Share this"));
}
This will let the user share the image + text to WhatsApp and all other apps the user wants, it's always the best to let the user select where to share the content instead of prompting just WhatsApp.
Also make sure that if you include just WhatsApp to share it might not be installed in some devices, for this you will need a try catch and inside of it the startActivity(intent); and also set the package of the intent to just WhatsApp with intent.setPackage("com.whatsapp").
Copy text from anywhere.let it be Google, Facebook or whatsapo itself
attempt to upload the image in whatsapp anywhere.at contact or group.before you hit the send image arrow... you will see caption option to that image... touch and hold, a paste option will appear.hit paste... your text will show up... then you can send the photo.and it will appear with the text you wanted... there you go... you have the text and image in it... the only problem will be the text size, which is limited to certain number of words
š This works for Android users only
I'm trying to add an image to my twitter share intent. I save an image locally in one class and then in another I get the image and try to attach to my intent.
Here is my code
private void shareTwitter(){
try {
FileInputStream fis;
fis = getActivity().openFileInput("photo.jpg");
Bitmap shot = BitmapFactory.decodeStream(fis);
File file = new File(MapView.path, "snapshot.jpg");
if(file.exists()){
Log.i("FILE", "YES");
}else{
Log.i("FILE", "NO");
}
Uri uri = Uri.parse(file.getAbsolutePath());
//Uri uri = Uri.parse("android.resource://com.gobaby.app/drawable/back");
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("/*");
intent.setClassName("com.twitter.android", "com.twitter.android.PostActivity");
intent.putExtra(Intent.EXTRA_TEXT, "Thiws is a share message");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(intent);
} catch (final ActivityNotFoundException e) {
Toast.makeText(getActivity(), "You don't seem to have twitter installed on this device", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
At the moment there is no exception in my logcat my app just displays a toast saying image failed to load.
Please what an I doing wrong?
This is what you need
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file);
This might be helpful for somebody:
private void sendShareTwit() {
try {
Intent tweetIntent = new Intent(Intent.ACTION_SEND);
String filename = "twitter_image.jpg";
File imageFile = new File(Environment.getExternalStorageDirectory(), filename);
tweetIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.twitter_share_text));
tweetIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile));
tweetIntent.setType("image/jpeg");
PackageManager pm = getActivity().getPackageManager();
List<ResolveInfo> lract = pm.queryIntentActivities(tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);
boolean resolved = false;
for (ResolveInfo ri : lract) {
if (ri.activityInfo.name.contains("twitter")) {
tweetIntent.setClassName(ri.activityInfo.packageName,
ri.activityInfo.name);
resolved = true;
break;
}
}
startActivity(resolved ?
tweetIntent :
Intent.createChooser(tweetIntent, "Choose one"));
} catch (final ActivityNotFoundException e) {
Toast.makeText(getActivity(), "You don't seem to have twitter installed on this device", Toast.LENGTH_SHORT).show();
}
}
Here is solution:
private fun shareOnTwitter() {
val file = File(context!!.filesDir, FILENAME_SHARE_ON_TWITTER)
val uriForFile = FileProvider.getUriForFile(context!!, com.yourpackage.activity.YourActivity, file)
val intent = Intent(Intent.ACTION_SEND).apply {
type = "image/jpeg"
putExtra(Intent.EXTRA_STREAM, uriForFile)
}
startActivity(intent)
}