FileDocCategorySizeDatePackage
ShareActionProvider.javaAPI DocAndroid 5.1 API13730Thu Mar 12 22:22:10 GMT 2015android.widget

ShareActionProvider

public class ShareActionProvider extends android.view.ActionProvider
This is a provider for a share action. It is responsible for creating views that enable data sharing and also to show a sub menu with sharing activities if the hosting item is placed on the overflow menu.

Here is how to use the action provider with custom backing file in a {@link MenuItem}:

// In Activity#onCreateOptionsMenu
public boolean onCreateOptionsMenu(Menu menu) {
// Get the menu item.
MenuItem menuItem = menu.findItem(R.id.my_menu_item);
// Get the provider and hold onto it to set/change the share intent.
mShareActionProvider = (ShareActionProvider) menuItem.getActionProvider();
// Set history different from the default before getting the action
// view since a call to {@link MenuItem#getActionView() MenuItem.getActionView()} calls
// {@link ActionProvider#onCreateActionView()} which uses the backing file name. Omit this
// line if using the default share history file is desired.
mShareActionProvider.setShareHistoryFileName("custom_share_history.xml");
. . .
}

// Somewhere in the application.
public void doShare(Intent shareIntent) {
// When you want to share set the share intent.
mShareActionProvider.setShareIntent(shareIntent);
}

Note: While the sample snippet demonstrates how to use this provider in the context of a menu item, the use of the provider is not limited to menu items.

see
ActionProvider

Fields Summary
private static final int
DEFAULT_INITIAL_ACTIVITY_COUNT
The default for the maximal number of activities shown in the sub-menu.
private int
mMaxShownActivityCount
The the maximum number activities shown in the sub-menu.
private final ShareMenuItemOnMenuItemClickListener
mOnMenuItemClickListener
Listener for handling menu item clicks.
public static final String
DEFAULT_SHARE_HISTORY_FILE_NAME
The default name for storing share history.
private final android.content.Context
mContext
Context for accessing resources.
private String
mShareHistoryFileName
The name of the file with share history data.
private OnShareTargetSelectedListener
mOnShareTargetSelectedListener
private android.widget.ActivityChooserModel.OnChooseActivityListener
mOnChooseActivityListener
Constructors Summary
public ShareActionProvider(android.content.Context context)
Creates a new instance.

param
context Context for accessing resources.


                   
       
        super(context);
        mContext = context;
    
Methods Summary
public booleanhasSubMenu()
{@inheritDoc}

        return true;
    
public android.view.ViewonCreateActionView()
{@inheritDoc}

        // Create the view and set its data model.
        ActivityChooserView activityChooserView = new ActivityChooserView(mContext);
        if (!activityChooserView.isInEditMode()) {
            ActivityChooserModel dataModel = ActivityChooserModel.get(mContext, mShareHistoryFileName);
            activityChooserView.setActivityChooserModel(dataModel);
        }

        // Lookup and set the expand action icon.
        TypedValue outTypedValue = new TypedValue();
        mContext.getTheme().resolveAttribute(R.attr.actionModeShareDrawable, outTypedValue, true);
        Drawable drawable = mContext.getDrawable(outTypedValue.resourceId);
        activityChooserView.setExpandActivityOverflowButtonDrawable(drawable);
        activityChooserView.setProvider(this);

        // Set content description.
        activityChooserView.setDefaultActionButtonContentDescription(
                R.string.shareactionprovider_share_with_application);
        activityChooserView.setExpandActivityOverflowButtonContentDescription(
                R.string.shareactionprovider_share_with);

        return activityChooserView;
    
public voidonPrepareSubMenu(android.view.SubMenu subMenu)
{@inheritDoc}

        // Clear since the order of items may change.
        subMenu.clear();

        ActivityChooserModel dataModel = ActivityChooserModel.get(mContext, mShareHistoryFileName);
        PackageManager packageManager = mContext.getPackageManager();

        final int expandedActivityCount = dataModel.getActivityCount();
        final int collapsedActivityCount = Math.min(expandedActivityCount, mMaxShownActivityCount);

        // Populate the sub-menu with a sub set of the activities.
        for (int i = 0; i < collapsedActivityCount; i++) {
            ResolveInfo activity = dataModel.getActivity(i);
            subMenu.add(0, i, i, activity.loadLabel(packageManager))
                .setIcon(activity.loadIcon(packageManager))
                .setOnMenuItemClickListener(mOnMenuItemClickListener);
        }

        if (collapsedActivityCount < expandedActivityCount) {
            // Add a sub-menu for showing all activities as a list item.
            SubMenu expandedSubMenu = subMenu.addSubMenu(Menu.NONE, collapsedActivityCount,
                    collapsedActivityCount,
                    mContext.getString(R.string.activity_chooser_view_see_all));
            for (int i = 0; i < expandedActivityCount; i++) {
                ResolveInfo activity = dataModel.getActivity(i);
                expandedSubMenu.add(0, i, i, activity.loadLabel(packageManager))
                    .setIcon(activity.loadIcon(packageManager))
                    .setOnMenuItemClickListener(mOnMenuItemClickListener);
            }
        }
    
private voidsetActivityChooserPolicyIfNeeded()
Set the activity chooser policy of the model backed by the current share history file if needed which is if there is a registered callback.

        if (mOnShareTargetSelectedListener == null) {
            return;
        }
        if (mOnChooseActivityListener == null) {
            mOnChooseActivityListener = new ShareActivityChooserModelPolicy();
        }
        ActivityChooserModel dataModel = ActivityChooserModel.get(mContext, mShareHistoryFileName);
        dataModel.setOnChooseActivityListener(mOnChooseActivityListener);
    
public voidsetOnShareTargetSelectedListener(android.widget.ShareActionProvider$OnShareTargetSelectedListener listener)
Sets a listener to be notified when a share target has been selected. The listener can optionally decide to handle the selection and not rely on the default behavior which is to launch the activity.

Note: If you choose the backing share history file you will still be notified in this callback.

param
listener The listener.

        mOnShareTargetSelectedListener = listener;
        setActivityChooserPolicyIfNeeded();
    
public voidsetShareHistoryFileName(java.lang.String shareHistoryFile)
Sets the file name of a file for persisting the share history which history will be used for ordering share targets. This file will be used for all view created by {@link #onCreateActionView()}. Defaults to {@link #DEFAULT_SHARE_HISTORY_FILE_NAME}. Set to null if share history should not be persisted between sessions.

Note: The history file name can be set any time, however only the action views created by {@link #onCreateActionView()} after setting the file name will be backed by the provided file. Therefore, if you want to use different history files for sharing specific types of content, every time you change the history file {@link #setShareHistoryFileName(String)} you must call {@link android.app.Activity#invalidateOptionsMenu()} to recreate the action view. You should not call {@link android.app.Activity#invalidateOptionsMenu()} from {@link android.app.Activity#onCreateOptionsMenu(Menu)}.

private void doShare(Intent intent) {
if (IMAGE.equals(intent.getMimeType())) {
mShareActionProvider.setHistoryFileName(SHARE_IMAGE_HISTORY_FILE_NAME);
} else if (TEXT.equals(intent.getMimeType())) {
mShareActionProvider.setHistoryFileName(SHARE_TEXT_HISTORY_FILE_NAME);
}
mShareActionProvider.setIntent(intent);
invalidateOptionsMenu();
}

param
shareHistoryFile The share history file name.

        mShareHistoryFileName = shareHistoryFile;
        setActivityChooserPolicyIfNeeded();
    
public voidsetShareIntent(android.content.Intent shareIntent)
Sets an intent with information about the share action. Here is a sample for constructing a share intent:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
Uri uri = Uri.fromFile(new File(getFilesDir(), "foo.jpg"));
shareIntent.putExtra(Intent.EXTRA_STREAM, uri));

param
shareIntent The share intent.
see
Intent#ACTION_SEND
see
Intent#ACTION_SEND_MULTIPLE

        if (shareIntent != null) {
            final String action = shareIntent.getAction();
            if (Intent.ACTION_SEND.equals(action) || Intent.ACTION_SEND_MULTIPLE.equals(action)) {
                shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
                        Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
            }
        }
        ActivityChooserModel dataModel = ActivityChooserModel.get(mContext,
            mShareHistoryFileName);
        dataModel.setIntent(shareIntent);