Last Updated: January 28, 2019
·
3.436K
· alberovalley

Simple share menu item

You have your app menu. You want some of your app's contents to be shared on the different social networks the user may have installed on his device with little fuss. Here's a simple way, done with actionbarsherlock so you can have it working on devices with Android 2.1+.

First, you need the menu item in your menu.xml file

<item
    android:id="@+id/my_share_item_id"
android:actionProviderClass="com.actionbarsherlock.widget.ShareActionProvider"
    android:icon="@android:drawable/ic_menu_share"
    android:menuCategory="my_category"
    android:orderInCategory="1"
    android:showAsAction="always"
    android:title="@string/menu_share"/>

Most attributes can change, except android:actionProviderClass.

In our activity, we inflate the menu

@Override
public boolean onCreateOptionsMenu(Menu menu) {

MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.menu_detalle_tapa, (Menu) menu);
MenuItem item = menu.findItem(R.id.ab_comparte);
mShareActionProvider = (ShareActionProvider) item.getActionProvider();

    this.menu = menu;
    return true;
}

In order to avoid the user attempting to share empty objects, we do this when all data has been set

/** Getting the target intent */
  Intent intent = getDefaultShareIntent();
  Log.d(CData.LOGTAG, "check if intent is null ");
  /** Setting a share intent */
  if(intent!=null)
      mShareActionProvider.setShareIntent(intent);
  else
      Log.d(CData.LOGTAG, "intent was null ");

Finally, we decide what's to be shared

private Intent getDefaultShareIntent(){

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
//this one won't show on twitter, for example, but will on emails.
intent.putExtra(Intent.EXTRA_SUBJECT, "SUBJECT");

String mySharedString = 
        myDataObject.getSomeField ;
intent.putExtra(Intent.EXTRA_TEXT,mySharedString);
return intent;
}

And that should do it.