Skip to content

Instantly share code, notes, and snippets.

@Mariovc
Last active June 9, 2023 17:24
Show Gist options
  • Save Mariovc/051391e92654de7b81d7 to your computer and use it in GitHub Desktop.
Save Mariovc/051391e92654de7b81d7 to your computer and use it in GitHub Desktop.
Utility to share text and url on Facebook, Twitter and Whatsapp
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
/**
* Author: Mario Velasco Casquero
* Date: 02/12/2015
*/
public class ShareUtils {
/**
* Share on Facebook. Using Facebook app if installed or web link otherwise.
*
* @param activity activity which launches the intent
* @param text not used/allowed on Facebook
* @param url url to share
*/
public static void shareFacebook(Activity activity, String text, String url) {
boolean facebookAppFound = false;
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, url);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));
PackageManager pm = activity.getPackageManager();
List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
for (final ResolveInfo app : activityList) {
if ((app.activityInfo.packageName).contains("com.facebook.katana")) {
final ActivityInfo activityInfo = app.activityInfo;
final ComponentName name = new ComponentName(activityInfo.applicationInfo.packageName, activityInfo.name);
shareIntent.addCategory(Intent.CATEGORY_LAUNCHER);
shareIntent.setComponent(name);
facebookAppFound = true;
break;
}
}
if (!facebookAppFound) {
String sharerUrl = "https://www.facebook.com/sharer/sharer.php?u=" + url;
shareIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(sharerUrl));
}
activity.startActivity(shareIntent);
}
/**
* Share on Twitter. Using Twitter app if installed or web link otherwise.
*
* @param activity activity which launches the intent
* @param text text to share
* @param url url to share
* @param via twitter username without '@' who shares
* @param hashtags hashtags for tweet without '#' and separated by ','
*/
public static void shareTwitter(Activity activity, String text, String url, String via, String hashtags) {
StringBuilder tweetUrl = new StringBuilder("https://twitter.com/intent/tweet?text=");
tweetUrl.append(TextUtils.isEmpty(text) ? urlEncode(" ") : urlEncode(text));
if (!TextUtils.isEmpty(url)) {
tweetUrl.append("&url=");
tweetUrl.append(urlEncode(url));
}
if (!TextUtils.isEmpty(via)) {
tweetUrl.append("&via=");
tweetUrl.append(urlEncode(via));
}
if (!TextUtils.isEmpty(hashtags)) {
tweetUrl.append("&hastags=");
tweetUrl.append(urlEncode(hashtags));
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(tweetUrl.toString()));
List<ResolveInfo> matches = activity.getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo info : matches) {
if (info.activityInfo.packageName.toLowerCase().startsWith("com.twitter")) {
intent.setPackage(info.activityInfo.packageName);
}
}
activity.startActivity(intent);
}
/**
* Share on Whatsapp (if installed)
*
* @param activity activity which launches the intent
* @param text text to share
* @param url url to share
*/
public static void shareWhatsapp(Activity activity, String text, String url) {
PackageManager pm = activity.getPackageManager();
try {
Intent waIntent = new Intent(Intent.ACTION_SEND);
waIntent.setType("text/plain");
PackageInfo info = pm.getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA);
//Check if package exists or not. If not then code
//in catch block will be called
waIntent.setPackage("com.whatsapp");
waIntent.putExtra(Intent.EXTRA_TEXT, text + " " + url);
activity.startActivity(Intent
.createChooser(waIntent, activity.getString(R.string.share_intent_title)));
} catch (PackageManager.NameNotFoundException e) {
Toast.makeText(activity, activity.getString(R.string.share_whatsapp_not_instaled),
Toast.LENGTH_SHORT).show();
}
}
/**
* Convert to UTF-8 text to put it on url format
*
* @param s text to be converted
* @return text on UTF-8 format
*/
public static String urlEncode(String s) {
try {
return URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
Log.wtf("wtf", "UTF-8 should always be supported", e);
throw new RuntimeException("URLEncoder.encode() failed for " + s);
}
}
}
@LeoYe168
Copy link

facebook share on web ?not on app ?

@Mariovc
Copy link
Author

Mariovc commented Jan 17, 2018

If the Facebook app is not found the intent is replaced for sharing on web, but if it is found the intent will be the one inside the for loop

@poorankharol
Copy link

text not retrieve at Facebook .

@Rajook
Copy link

Rajook commented Feb 15, 2019

these all are very nice can you please add G+ and Pinterest share methods.

@calmerman
Copy link

calmerman commented Apr 26, 2019

I found my url or text not retrieve at Facebook , https://stackoverflow.com/questions/7545254/android-and-facebook-share-intent

@AndresGarciaSobrado91
Copy link

AndresGarciaSobrado91 commented Jul 17, 2019

Thank you!

text not retrieve at Facebook .

The only way is to copy text to cplipboard and ask the user to paste it. So Sad, Facebook does not permit any more to share text from android intent.

android.content.ClipboardManager clipboard = (android.content.ClipboardManager) activity.getSystemService(activity.CLIPBOARD_SERVICE);
        android.content.ClipData clip = android.content.ClipData.newPlainText("facebook",text);
        clipboard.setPrimaryClip(clip);

activity.startActivity(shareIntent);

        Toast toast = Toast.makeText(activity,"Please, long press and paste on top of the link. Thank you!",Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL,0,0);
        toast.show();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment