Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Android action bar share intent

I'm using a menu item on the action bar and I want to share my app by clicking the share icon. When I click the share icon it doesn't work. Also, I want to add text saying "install this app" when shared.

Here is my code:

private ShareActionProvider mShareActionProvider;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.mainpage, menu);
    MenuItem item = menu.findItem(R.id.menu_item_share);
    mShareActionProvider = (ShareActionProvider) item.getActionProvider();

    return true;
}

private void setShareIntent(Intent shareIntent) {
    if (mShareActionProvider != null) {
        mShareActionProvider.setShareIntent(shareIntent);
    }
}

Mainpage.xml menu:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/menu_item_share"
    android:showAsAction="ifRoom"
    android:title="Share"
    android:icon="@drawable/ic_store"
    android:actionProviderClass="android.widget.ShareActionProvider" />
</menu>
like image 903
Bachim01 Avatar asked Nov 19 '25 18:11

Bachim01


2 Answers

If you want a static share Intent (i.e., it never changes), then you update your onCreateOptionsMenu to be

public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.mainpage, menu);
    MenuItem item = menu.findItem(R.id.menu_item_share);
    mShareActionProvider = (ShareActionProvider) item.getActionProvider();
    // Create the share Intent
    String playStoreLink = "https://play.google.com/store/apps/details?id=" +
        getPackageName();
    String yourShareText = "Install this app " + playStoreLink;
    Intent shareIntent = ShareCompat.IntentBuilder.from(this)
        .setType("text/plain").setText(yourShareText).getIntent();
    // Set the share Intent
    mShareActionProvider.setShareIntent(shareIntent);
    return true;
}
like image 170
ianhanniballake Avatar answered Nov 22 '25 09:11

ianhanniballake


you can get the official tutorial here http://developer.android.com/guide/topics/ui/actionbar.html#ActionProvider

In the snappet you paste, you forget to call

mShareActionProvider.setShareIntent(intent);
like image 45
hoot Avatar answered Nov 22 '25 08:11

hoot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!