15

I've created an application which shares to facebook, twitter etc. But I want to perform different functions dependent on who the user is sharing to, for instance if the user is sharing to Facebook do one thing but if the user shares to twitter do another.

How do I do this?

My code so far is below:

private void ShareSub() {
    Intent i = new Intent(Intent.ACTION_SEND);
    i.setType("text/plain");
    i.putExtra(
            Intent.EXTRA_TEXT,
            "You've just shared "
                    + "Awesome");
    startActivity(i);
}

Further explanation of above code:

When the user presses the "menu_item_share" button in the action bar, the function above is triggered. This function then makes a box like the image below appear, which allows the user to select a particular option, e.g. Facebook or twitter. The Intent.EXTRA_TEXT is then shared to that particular app.

What I'm wanting is, when the user clicks for instance Facebook, a particular function is called e.g. Sharing via their (Facebook's) api etc.

enter image description here

I'm not using ShareActionProvider like below:

   <item
        android:id="@+id/your_share_item"
        android:actionProviderClass="android.widget.ShareActionProvider"
        android:showAsAction="ifRoom"
        android:title="@string/share"/>

Instead, I've created a simple button which calls the function ShareSub:

<item
    android:id="@+id/menu_item_share"
    android:icon="@android:drawable/ic_menu_share"
    android:showAsAction="ifRoom"
    android:title="Share"/>

The reason I've chosen to do it this way is, I don't want the recently shared to button to appear, as in the image below. This is causing me problems when I attempt to use the code suggested below because I haven't used ShareActionProvider.

enter image description here

AZ_
  • 21,688
  • 25
  • 143
  • 191
  • Crossposted: http://www.java-forums.org/android/87941-android-how-do-i-detect-if-user-has-chosen-share-facebook-twitter.html – Kevin Workman May 06 '14 at 12:28
  • 1
    No answer was given there, so I came here. Are you able to solve the above? –  May 06 '14 at 12:29
  • 2
    No, I wouldn't do that. If someone had answered me on that forum, I then would then place a link here with the answer. So other users could benefit from the answer. But that wasn't the case. - No answers were given there. –  May 06 '14 at 12:33

4 Answers4

22

You can't directly find out which app was chosen, but you can display your own Chooser dialog.

Instead of calling startActivity(i), get a list of all activities (facebook, twitter etc) that are registered to handle your intent using queryIntentActivities().

List<ResolveInfo> activities = getPackageManager().queryIntentActivities (i, 0);

Each ResolveInfo is an app that can handle your intent. Now you can show an AlertDialog containing a list of labels or icons. When the user selects a label from the list, you can handle what do to on an app-specific basis in the click handler for the dialog.

EDIT: Here's a full working example

private void ShareSub() {
    final Intent i = new Intent(Intent.ACTION_SEND);
    i.setType("text/plain");
    i.putExtra(Intent.EXTRA_TEXT,"text");

    final List<ResolveInfo> activities = getPackageManager().queryIntentActivities (i, 0);

    List<String> appNames = new ArrayList<String>();
    for (ResolveInfo info : activities) {
        appNames.add(info.loadLabel(getPackageManager()).toString());
    }

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Complete Action using...");
    builder.setItems(appNames.toArray(new CharSequence[appNames.size()]), new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {
            ResolveInfo info = activities.get(item);
            if (info.activityInfo.packageName.equals("com.facebook.katana")) {
                // Facebook was chosen
            } else if (info.activityInfo.packageName.equals("com.twitter.android")) {
                // Twitter was chosen
            }

            // start the selected activity
            i.setPackage(info.activityInfo.packageName);
            startActivity(i);
        }
    });
    AlertDialog alert = builder.create();
    alert.show();
}
Community
  • 1
  • 1
Nachi
  • 4,218
  • 2
  • 37
  • 58
  • That is what happens here, a button is placed on the actionbar. Upon pressing, a popup appears with several options (Facebook, gmail, twitter etc.) How do I detect whether the user has chosen twitter for instance and activate a particular function –  May 06 '14 at 12:41
  • I edited my answer to clarify this. The options (Facebook, gmail, twitter etc.) are all displayed by Android and are outside your app's control. But if you query this list beforehand and show it in your own custom "Complete Action using..." dialog, you can eventually find out which option the user clicked on. – Nachi May 06 '14 at 12:47
  • Do you know of any examples of this, as obviously I am very stuck on the above –  May 06 '14 at 13:24
  • What are you exactly stuck on? – Nachi May 06 '14 at 13:48
  • I can't detect when the user has selected Facebook from the share menu as above, then execute a particular function. My major issue is, as the all of the solutions offered so far make use of ShareActionProvider they won't work for me as I haven't used this (as explained above) –  May 06 '14 at 13:52
  • 1
    It sounds good theoretically, but I've not created an AlertDialog like you're describing before, so that isn't very clear. Which is why I asked whether you knew of any examples where your idea was shown? –  May 06 '14 at 14:01
  • this code works like a charm. But I can't see the application icons ! – emresancaktar Mar 30 '15 at 09:03
  • 2
    This is a basic example that only uses application names. Use [ResolveInfo.loadIcon](http://developer.android.com/reference/android/content/pm/ResolveInfo.html#loadIcon(android.content.pm.PackageManager)) to add an icon drawable to your list. – Nachi Mar 30 '15 at 09:34
  • 2
    TO BE NOTED: We can't make sure if the share is succeed or cancelled by the user. – HendraWD Oct 06 '16 at 04:35
8

Use presses a button in the action bar which triggers the above function.

If you used a ShareActionProvider instead, you could detect when a user selects a particular app from the list by implementing a ShareActionProvider.OnShareTargetSelectedListener. Otherwise you won't be able to detect which app is selected unless you implement your own activity chooser.

Here's an example:

menu

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/your_share_item"
        android:actionProviderClass="android.widget.ShareActionProvider"
        android:showAsAction="ifRoom"
        android:title="@string/share"/>

</menu>

Implementation

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate your menu
    getMenuInflater().inflate(R.menu.share, menu);

    // The Intent you want to share
    final Intent i = new Intent(Intent.ACTION_SEND);
    i.setType("text/plain");
    i.putExtra(Intent.EXTRA_TEXT, "Test");

    // Set up your ShareActionProvider
    final ShareActionProvider shareActionProvider = (ShareActionProvider) menu.findItem(
            R.id.your_share_item).getActionProvider();
    shareActionProvider.setShareIntent(i);
    shareActionProvider.setOnShareTargetSelectedListener(new OnShareTargetSelectedListener() {

        @Override
        public boolean onShareTargetSelected(ShareActionProvider source, Intent intent) {
            final String packageName = intent.getComponent().getPackageName();
            if (packageName.equals("com.facebook.katana")) {
                // Do something for Facebook
            } else if (packageName.equals("com.twitter.android")) {
                // Do something for Twitter
            }
            return false;
        }

    });
    return super.onCreateOptionsMenu(menu);
}
adneal
  • 30,484
  • 10
  • 122
  • 151
  • I should have clarified the reason I've created a button in the action bar to call a function rather than the above is. I don't want the 2nd button telling the user the last app he shared to, to be created. I've updated thread above and explained. - the above code will not work for that reason –  May 06 '14 at 13:26
  • 1
    BUt we can not modify Intent here. check https://developer.android.com/reference/android/widget/ShareActionProvider.OnShareTargetSelectedListener.html#onShareTargetSelected%28android.widget.ShareActionProvider,%20android.content.Intent%29 – sandeepmaaram Dec 05 '14 at 04:26
  • This solution works great, but how to control the behaviour in case of Facebook? For example i want to handle the facebook share manually, but it is still showing the facebook share dialog. – Shajeel Afzal Jun 18 '16 at 10:31
  • This sample code is useful to check quick demonstration of this answer, it really worked for me. http://stackandroid.com/tutorial/android-shareactionprovider-tutorial/ – Farhan Apr 26 '17 at 09:52
1

Although this question has an accepted answer, things have changed, and now there is a better approach, which is the recommended way of achieving this.

Using "Android Sharesheet"

Here's the documentation: https://developer.android.com/training/sharing/send#share-interaction-data

While creating the IntentChooser, you can pass a pending intent, which will trigger a broadcast receiver within your app.

The data provided by the onReceive method of that Broadcast Receiver will give you the name of the component that was used to handle the SEND intent.

Code for adding a pending intent to the SEND intent:

Intent share = new Intent(ACTION_SEND);
...
PendingIntent pi = PendingIntent.getBroadcast(myContext, requestCode,
        new Intent(myContext, MyBroadcastReceiver.class),
        PendingIntent.FLAG_UPDATE_CURRENT);
share = Intent.createChooser(share, null, pi.getIntentSender());

Code for retrieving the details of the component that was chosen by the user:

@Override public void onReceive(Context context, Intent intent) {
  ...
  ComponentName clickedComponent = intent.getParcelableExtra(EXTRA_CHOSEN_COMPONENT);
}
Kumar Bibek
  • 9,016
  • 2
  • 39
  • 68
0

Try that answers: here choose the define intent which you want:

Customize Android Intent.ACTION_SEND

Branching the Android Share Intent extras depending on which method they choose to share

Android - How to filter specific apps for ACTION_SEND intent

Community
  • 1
  • 1
Engr Waseem Arain
  • 1,163
  • 1
  • 17
  • 36
  • I've tried each of those, but for some reason all they do is activate the Facebook code straight away when the user clicks the share button in the actionbar rather than if he selects Facebook from the list –  May 06 '14 at 13:09
  • Follow that answers correctly, i have already used that work fine – Engr Waseem Arain May 06 '14 at 13:10
  • They don't work when you're not using ShareActionProvider, which i'm not using for the above reasons. –  May 06 '14 at 13:14
  • Simply use avoid that and share with use api of facebook: https://developers.facebook.com/ – Engr Waseem Arain May 06 '14 at 13:20
  • I've already written the code to share with Facebook. That I know hence my question. The bit I'm stuck on is, having the program upon click of Facebook in the share box as above, run the subroutine containing facebook api code –  May 06 '14 at 13:26