Skip to content

Instantly share code, notes, and snippets.

@AndresGarciaSobrado91
Forked from Mariovc/ShareUtils.java
Last active December 5, 2019 22:23
Show Gist options
  • Save AndresGarciaSobrado91/8ef83d7dcfcaf4b8fa758952ec2ac58d to your computer and use it in GitHub Desktop.
Save AndresGarciaSobrado91/8ef83d7dcfcaf4b8fa758952ec2ac58d to your computer and use it in GitHub Desktop.
Utility to share text and url on Facebook, Twitter and Whatsapp -> Fixed text never showed on Facebook and SMS share added
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.view.Gravity;
import android.widget.Toast;
import com.delyva.partnerapp.R;
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));
}
//Text copied to clipboard because Facebook doesn't permit to add text from intent. It must be done manually.
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();
}
/**
* 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, "Share on WhatsApp"));
} catch (PackageManager.NameNotFoundException e) {
Toast.makeText(activity, "Sorry, WhatsApp is not installed",
Toast.LENGTH_SHORT).show();
}
}
public static void shareSMS(Activity activity, String text, String url, String receiver) {
Intent intent = new Intent("android.intent.action.VIEW");
Uri data = Uri.parse("sms: " + receiver);
intent.putExtra("sms_body", text + " " + url);
intent.setData(data);
try
{
activity.startActivity(intent);
}
catch(Exception e)
{
Toast.makeText(activity,e.getMessage(),Toast.LENGTH_LONG).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);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment