Capturing and intercepting ACTION_SEND intents on Android
Currently I have a pretty standard ACTION_SEND intent to share information from inside my app. Code is similar to what is below:
Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, subject); intent.putExtra(Intent.EXTRA_TEXT, text); context.startActivity(Intent.createChooser(intent, title));
Now, if the user has the Facebook app installed on their phone then Facebook shows up as an option for the intent chooser. However, I want to intercept the user's click on "Facebook" and use the Facebook SDK to carry out the task instead of the Facebook application already on the users phone. Is there a way to intercept the onClick for the Facebook option? Thanks!
Here is a link to my blog post with a detailed solution, including code and screen shots.
As quoted from that article:
[W]e first create a new action_send intent and set the type to text/plain. Next, we create a List. We make the call to the package manager to query for all Activities with the action_send intent registered. This call returs a list of ResolveInfo objects, each corresponding to an Activity on the device that claims to handle send actions.
[Then, r]ather than launching the action_send intent and letting it create its own dialog (one that we would have no control over), we will build our own with the AlertDialog.Builder. First we give it a title, then set its adapter to the list adapter we just created with the activities list as our data set[.]
The next important piece we need to look at is the OnClick listener we gave the Builder. To find which item the user clicked, we use the adapter.getItem(int which) method. This will return the object in that position of our original list, in this case, a ResolveInfo object corresponding to the selected Activity. For my case in particular, I only care about separating things into two groups: Facebook and not Facebook. To do this, I simply check if the selected Activity’s package name contains ‘facebook’. If it does not, I create a new action_send intent, set the class name to the selected activity, and launch it. However, if the package name DOES contain ‘facebook’, I instantiated my personal PostToFacebookDialog object which will create a basic Android dialog with post and cancel buttons, and will post to Facebook directly using the Graph API, thus circumventing the user’s installed Facebook app.