- Sharing Content between Android apps
- Sharing text
- Sharing HTML text
- Receiving text
- Sharing files and images
- Receiving files
- The Support Library is your friend
- Sharing Content with Intents
- Night Dreaming (by Sudar)
- Sharing content in Android using ACTION_SEND Intent
- Sharing text
- Sharing binary objects (Images, videos etc.)
- Registering for the Intent
- Related posts
- 86 Comments so far
Sharing Content between Android apps
Sharing is caring, as they say, but sharing on Android means something perhaps slightly different. ‘Sharing’ is really shorthand for sending content such as text, formatted text, files, or images between apps.
So if ‘sharing’ == sending content, it makes slightly more sense that it is implemented using ACTION_SEND (or ACTION_SEND_MULTIPLE) Intents and its dozen extras.
While that approach is perfectly valid, I prefer to use ShareCompat, a set of classes in the v4 Support Library designed to make it easy to build intents for sharing content.
Sharing text
Sharing plain text is, as you might imagine, a good place to start. In fact, there’s not a whole lot to it:
ShareCompat.IntentBuilder uses a fluent API where you can chain together multiple method calls, using only the ones you need. For sharing, one of the most important parts is picking the right mime type — this is how apps filter what type of content they can receive. By using text/plain, we signify that our Intent will only contain plain text. Then, of course, setText() is how we actually add the CharSequence to the Intent to send. And while you can certainly send styled text using setText(), there’s no guarantee that the receiving app will honor that styling, so you should ensure that the text is legible with or without styling.
You’ll note we then use resolveActivity() before calling startActivity(). As mentioned in Protecting Implicit Intents with Runtime Checks, this is critical to prevent an ActivityNotFoundException when there is no Activity available to handle the mime type you have selected. While probably not as much of a concern with text/plain, it may be much more common with other types.
Note: when you use startActivity(shareIntent), that respects any default apps the user has set (i.e., if they’ve previously selected sharing all “text/plain” items to a certain app). If you’d like to instead always show a disambiguation chooser, use the intent generated from IntentBuilder.createChooserIntent() as explained in the ACTION_CHOOSER documentation.
Sharing HTML text
Some apps, most notably email clients, also support formatting with HTML. The changes, compared to plain text, are fairly minor:
The differences here are that we use of setHtmlText() in place of setText() and a mime type of text/html replacing text/plain. Here ShareCompat actually does a little bit extra: setHtmlText() also uses Html.fromHtml() to create a fallback formatted text to pass along to the receiving app if you haven’t previously called setText() yourself.
Given that many of the apps that can receive HTML text are email clients, there’s a number of helper methods to set the subject, to:, cc:, and bcc: email addresses as well — consider adding at least a subject to any share intent for best compatibility with email apps.
Of course, you’ll still want to call resolveActivity() just as before — nothing changes there.
Receiving text
While the focus so far has been on the sending side, it is helpful to know exactly what is happening on the other side (if not just to build a simple receiving app to install on your emulator for testing purposes). Receiving Activities add an intent filter to the Activity:
The action is obviously the more critical part — without that there’s nothing that would denote this as an ACTION_SEND (the action behind sharing). The mime type, same as with our sending code, is also present here. What isn’t as obvious are the two categories. From the element documentation:
Note: In order to receive implicit intents, you must include the CATEGORY_DEFAULT category in the intent filter. The methods startActivity() and startActivityForResult() treat all intents as if they declared the CATEGORY_DEFAULT category. If you do not declare it in your intent filter, no implicit intents will resolve to your activity.
So CATEGORY_DEFAULT is required for our use case. Then, CATEGORY_BROWSABLE allows web pages to natively share into apps without any extra effort required on the receiving side.
And to actually extract the information from the Intent, the useful ShareCompat.IntentReader can be used:
Similar to IntentBuilder, IntentReader is just a simple wrapper that make it easy to extract information.
Sharing files and images
While sending and receiving text is straightforward enough (create text, include it in Intent), sending files (and particularly images — the most common type by far) has an additional wrinkle: file permissions.
The simplest code you might try might look like
And that almost works — the tricky part is in getting a Uri to the File that other apps can actually read, particularly when it comes to Android 6.0 Marshmallow devices and runtime permissions (which include the now dangerous READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE permissions).
My plea: don’t use Uri.fromFile(). It forces receiving apps to have the READ_EXTERNAL_STORAGE permission, won’t work at all if you are trying to share across users, and prior to KitKat, would require your app to have WRITE_EXTERNAL_STORAGE. And really important share targets, like Gmail, won’t have the READ_EXTERNAL_STORAGE permission — so it’ll just fail.
Instead, you can use URI permissions to grant other apps access to specific Uris. While URI permissions don’t work on file:// URIs as is generated by Uri.fromFile(), they do work on Uris associated with Content Providers. Rather than implement your own just for this, you can and should use FileProvider as explained in the File Sharing Training.
Once you have it set up, our code becomes:
Using FileProvider.getUriForFile(), you’ll get a Uri actually suitable for sending to another app — they’ll be able to read it without any storage permissions — instead, you are specifically granting them read permission with FLAG_GRANT_READ_URI_PERMISSION.
Note: we don’t call setType() anywhere when building our ShareCompat (even though in the video I did set it). As explained in the setDataAndType() Javadoc, the type is automatically inferred from the data URI using getContentResolver().getType(uriToImage). Since FileProvider returns the correct mime type automatically, we don’t need to manually specify a mime type at all.
If you’re interested in learning more about avoiding the storage permission, consider watching my Forget the Storage Permission talk or at least go through the slides, which covers this topic in depth at 14:55 (slide 11).
Receiving files
Receiving files isn’t too different from text because you’re still going to use ShareCompat.IntentReader. For example, to make a Bitmap out of an incoming file, it would look like:
Of course, you’re free to do whatever you want with the InputStream — watch out for images that are so large you hit an OutOfMemoryException. All of the things you know about loading Bitmaps still apply.
The Support Library is your friend
With both ShareCompat (and its IntentBuilder and IntentReader) and FileProvider in the v4 Support Library, you’ll be able to include sharing text, HTML text, and files in your app with the best practices by default.
Источник
Sharing Content with Intents
Intents allow us to communicate data between Android apps and implicit intents can also accept actions. One of those actions is the ACTION_SEND command which indicates we want to send data across apps. To send data, all you need to do is specify the data and its type, and the system will identify compatible receiving activities and display them to the user.
Sending and receiving data between applications with intents is most commonly used for social sharing of content. Intents allow users to share information quickly and easily, using their favorite applications.
You can send content by invoking an implicit intent with ACTION_SEND .
To send images or binary data:
Sending URL links should simply use text/plain type:
In certain cases, we might want to send an image along with text. This can be done with:
Sharing multiple images can be done with:
See this stackoverflow post for more details.
Note: Facebook does not properly recognize multiple shared elements. See this facebook specific bug for more details and share using their SDK.
Facebook doesn’t work well with normal sharing intents when sharing multiple content elements as discussed in this bug. To share posts with facebook, we need to:
- Create a new Facebook app here (follow the instructions)
- Add the Facebook SDK to your Android project
- Share using this code snippet:
You may want to send an image that were loaded from a remote URL. Assuming you are using a third party library like Glide, here is how you might share an image that came from the network and was loaded into an ImageView. There are two ways to accomplish this. The first way, shown below, takes the bitmap from the view and loads it into a file.
and then later assuming after the image has completed loading, this is how you can trigger a share:
Make sure to setup the «SD Card» within the emulator device settings:
Note that if you are using API 24 or above, see the section below on using a FileProvider to work around new file restrictions.
If you are targeting Android API 24 or higher, private File URI resources (file:///) cannot be shared. You must instead wrap the File object as a content provider (content://) using the FileProvider class.
First, you must declare this FileProvider in your AndroidManifest.xml file within the tag:
Next, create a resource directory called xml and create a fileprovider.xml . Assuming you wish to grant access to the application’s specific external storage directory, which requires requesting no additional permissions, you can declare this line as follows:
Finally, you will convert the File object into a content provider using the FileProvider class:
If you see a INSTALL_FAILED_CONFLICTING_PROVIDER error when attempting to run the app, change the string com.codepath.fileprovider in your Java and XML files to something more unique, such as com.codepath.fileprovider.YOUR_APP_NAME_HERE .
Note that there are other XML tags you can use in the fileprovider.xml , which map to the File directory specified. In the example above, we use Context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) , which corresponded to the XML tag in the declaration with the Pictures path explicitly specified. Here are all the options you can use too:
XML tag | Corresponding storage call | When to use |
---|---|---|
Context.getFilesDir() | data can only be viewed by app, deleted when uninstalled ( /data/data/[packagename]/files ) | |
Context.getExternalFilesDir() | data can be read/write by the app, any apps granted with READ_STORAGE permission can read too, deleted when uninstalled ( /Android/data/[packagename]/files ) | |
Context.getCacheDir() | temporary file storage | |
Environment.getExternalStoragePublicDirectory() | data can be read/write by the app, any apps can view, files not deleted when uninstalled | |
Context.getExternalCacheDir() | temporary file storage with usually larger space |
If you are using API 23 or above, then you’ll need to request runtime permissions for Manifest.permission.READ_EXTERNAL_STORAGE and Manifest.permission.WRITE_EXTERNAL_STORAGE in order to share the image as shown above since newer versions require explicit permisions at runtime for accessing external storage.
Note: There is a common bug on emulators that will cause MediaStore.Images.Media.insertImage to fail with E/MediaStore﹕ Failed to insert image unless the media directory is first initialized as described in the link.
This is how you can easily use an ActionBar share icon to activate a ShareIntent. The below focuses on the support ShareActionProvider for use with AppCompatActivity .
Note: This is an alternative to using a sharing intent as described in the previous section. You either can use a sharing intent or the provider as described below.
First, we need to add an ActionBar menu item in res/menu/ in the XML specifying the ShareActionProvider class.
Next, get access to share provider menu item in the Activity so we can attach the share intent later:
Note: ShareActionProvider does not respond to onOptionsItemSelected() events, so you set the share action provider as soon as it is possible.
Now, once you’ve setup the ShareActionProvider menu item, construct and attach the share intent for the provider but only after image has been loaded as shown below using the RequestListener for Glide .
Note: Be sure to call attachShareIntentAction method both inside onCreateOptionsMenu AND inside the onResourceReady for Glide to ensure that the share attaches properly.
We can use a similar approach if we wish to create a share action for the current URL that is being loaded in a WebView:
Check out the official guide for easy sharing for more information.
Источник
Night Dreaming (by Sudar)
You are here: Home » » Blog » Sharing content in Android using ACTION_SEND Intent
Sharing content in Android using ACTION_SEND Intent
Very often, you might want to enable the ability for users to share some content (either text, link or an image) from your Android app. Users can share the content using email, twitter, Facebook, sms or through numerous other ways.
The users might already have installed some custom apps for each one of the above service. So instead of coding all these again, it would be really nice (for both your users as well as for you as a developer) if you can invoke any one of these apps, where users want to share content from your app.
Sharing text
Android provides a built-in Intent called ACTION_SEND for this purpose. Using it in your app is very easy. All you have to do is to use the following couple of lines.
In my phone, it invokes the following dialog box listing the apps that have registered to get notification for this intent.
Sharing binary objects (Images, videos etc.)
In addition to supporting text, this intent also supports sharing images or any binary content. All you have to do is to set the appropriate mime type and then pass the binary data by calling the putExtra method.
Registering for the Intent
If you want your app to be listed when this Intent is called, then you have to add an intent filter in your manifest.xml file
android:mimeType specifies the mime type which you are interested in listening.
Related posts
86 Comments so far
Thank you for this tuto, it’s very clear.
My problem is I don’t know java…
I’m using App Inventor to create my applications,
as a newbie I’m struggling to find out a way to call the sharing list which is exactly what you are describing here, but it seems that no one knows (or at least shares) yet how to do it in AI (apparently with “activity starter” component but how?).
Would it be possible for you to give us some ideas ? That would be much appreciated for us as AI users.
I am not sure if this can be done using App Inventor.
Thanks, amazing information!
So if I wanted to sent an array of binary bytes, what would the appropriate mime type be?
Thanks for this useful guidelines. Am new to this Android application coding. I need a small favor, actually out of those items “Facebook, Gmail, Mail, Messages and Peep”. is it possible to display only “Facebook, Gmail”. I need answer for this very much in urgent, Kindly do help me out in this. Thanks in advance
This will list down all applications that have registered to receive that Intend. If you need only a few, then you may have to implement the entire menu yourself as part of your application.
Share your adventures, photos with Gowalla Android app.
hi Sudar,
thanks for sharing your knowledge.
How can we copy and paste like functionality for Images.
Using ClipBoard we can copy text that I know.
pls suggest me way to do this.
Hello
I had used your app and able to launch Sharing Screen as you shown but it is not working means[Functionality].
Like selecting Bluetooth its able to Scan Device but not getting connected.
Check your error log and let me know if you are getting any exceptions there.
Hi, I want show the HTML file on facebook wall and did the same as above but the share option menu showing only mail, gmail and bluetooth. It’s not showing facebook or other options.
Note: I have included the code in menifest too.
Do you have any Facebook app installed in your phone or emulator?
Yes, I have already installed facebook app for android. Thanks
for setType(“text/html”) facebook app is not showing in list. And if i user “text/plain” facebook twitter apps shows. But in facebook my data has not been sent and blank string will display in facebook app.
Any help will be appreciated. I want to send message in facebook app.
It seems that only urls can be shared in facebook, your texts does not appear.
Facebook doesn’t allow text to be shared directly. In order to do that you have to incorporate the Facebook SDK also.
Thanks for the article.
It turns Sharing content in Android is easy.
Thanks a lot….superb code
Thanks a lot for the post, but the code opens up a text editor on my device. Any suggestions on what am missing out?
> If you want your app to be listed
And why would I want (or not want) this optional “listed” thing?
hi i am d learner….plz mail d code… Were i wll get this code to download……..
@Carol: Listed in the list of applications which are displayed if an sharing intent is triggered.
Thanks for this useful guidelines. Am new to this Android application coding. I need a small favor, actually out of those items “Facebook, Gmail, Mail, Messages and Peep”. is it possible to display only “Facebook, Gmail”. Kindly do help me out in this. Thanks in advance
That’s not possible, since Android builds this list based on the list of apps that are installed in the phone.
i want to do when data share by intent using above code then how i receive data shared by intent. any one help me
how i get data shared by intent using broadcast receiver.
hi,
i want to create a new app,here the main thing is to share the images.
It has the online chatting feature so whille chatting i want to share images
to a perticular online member.Please give me some idea about this.
Thanks in advance.
This is very useful, thanks!
After trying this code, i was able to embed sharing, but the SMS option (Messaging) did not appear.
What’s the trick ?
hello. can I do this share list in php?
You can’t run PHP code in Android.
You not understand me.
I’m want to run this code in front-end of wordpress site.
Is it possible?
No it is not possible. This is an Android app code which can only run in an Android device.
you mention a possibility of sharing a link, but your example doesnt feature code explaining how to do link sharing. is it just a case of checking the “sent text” to see if it is a URL somehow or is there a specific intent filter for dealing with links/urls?
You might also have to change the mime:type.
Its HelpFull But I have Confuse Where I can Start.When i Click menu button show options menu in that share option select show the dialog what shown above how to integrate all in to my application please provide the step by step process for sharing image .
not working on facebook and linkedin,whtasapp, viber etc.
only working in email/gmail
Sharing an image (binary object) only works if the image is stored on the sd card (not in getFilesDir() oder getCacheDir() directories)! Otherwise there’s an error saying “could not add image to your message” (if shared with a messaging service).
hi how can i share to facebook only ?
hii iam developing android application using phone gap. Iam struggling to add native Share in my application.. can u help me how to add ACTION_SEND code in Phone Gap?? is it possible?? thanks in advance
well i looking for sharing data between two devices using share intent. is it possible kindly reply ASAP
Thanks in Advance
Please tell me how to add images that are from drawable folder to alertdialog using java… thank you sir for your support
Thanks for this information actually i was making an android app for New year, in that i want to share, SMS and greetings using facebook, twitter and whatsapp.. Thanks using this article i am able to do it, Actually i have made my app on App inventor. But the intent commands have helped me a lot to do what i decided with my app. 🙂
i use the uri is Uri.parse(“android.resource://” + getPackageName()
+ “/drawable/” + “p1”)
HI
All things work only facebook not share the text content.
I think it looks like it is helpful. I thank you for that, but it has lack of details to new developers like me. Anyways, after I tried what you showed us, it worked 60%, so I had to Google in stackoverflaw and I found this that helped me solving 40% of my problems. Here is the code:
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType(“text/plain”);
String shareBody = “This is a test”;
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, “You have to see this!”);
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivityForResult(Intent.createChooser(sharingIntent, “Share via”),1);
Viber not send image ..
bellow is my code:
Intent share_Intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
share_Intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,
selectedList);
share_Intent.setType(“image/jpeg”);
share_Intent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(Intent.createChooser(share_Intent,
“Share_image_using”));
its not working for viber
Its not working for viber Image Sharing :
Image not Load when we share image in viber
I Solved the Problem of Viber photo sharing :
selectedList = new ArrayList();
for (int i = 0; i android says:
I am having an error sharing text,
error log says: Are you missing a call to unragister reciever….
I am learning fresh, can anyone tell what am i missing here??
“01-08 19:39:10.839: E/ActivityThread(17216): android.app.IntentReceiverLeaked: Activity com.android.internal.app.ChooserActivity has leaked IntentReceiver com.android.internal.app.ResolverActivity$1@418b4fa0 that was originally registered here. Are you missing a call to unregisterReceiver()?”
Can you post the part of your source code where you are getting this error in pastebin or gist.github.com and then post a link here?
I am not seeing facebook, messenger, whatsapp in the options when I use this code even though the apps are installed in my mobile. Any idea why this is the case?
Sir I want to send a 3 sec sound on intent.. How could I do it using intent.. What should I write in put extras method.. Need help.. Wat should I write in set type.
Thanks are very beautiful and practical
You fail to tell which file and where in that file these pieces of code are to be placed.
The code goes into your Activity classes.
Thanks ….. It was very good
Mobile click-to-call functionality is a great way to capture call data without needing a special tracking number
way to capture call data without needing a special tracking number
Hi Sudar,
I am trying to send an image file from one android phone to another phone using bluetooth. My requirement is to send a specified file to specified devices only. I don’t want any user interaction in between. I am using action_send intent and pls find below the code. The problem I am getting is that it is displays the list of devices and expect me to select a bluetooth device and t he specified file is transferred. I am struggling to find a solution for the last 3 weeks and any help would be much appreciated.
code:
File f = new File(Environment.getExternalStorageDirectory(),”test1.jpg”);
Intent sendIntent = new Intent(Intent.ACTION_SENDTO);
sendIntent.setType(“image/*”);
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
sendIntent.putExtra(BluetoothDevice.EXTRA_DEVICE, device.getAddress());
// sendIntent.setClassName(“com.android.bluetooth”, “com.broadcom.bt.app.opp.OppLauncherActivity”);
//sendIntent.setClassName(“com.android.bluetooth”, “com.android.bluetooth.opp.BluetoothOppLauncherActivity”);
sendIntent.setPackage(“com.android.bluetooth”);
startActivity(sendIntent);
and my manifest file looks:
Some of your code got truncated.
Can you post about this in Stackoverflow?
Hi,
Were you able to do that finally? Now I am struggling with the same problem…
Hi
I want to share some let you edit text. Code share one of them I know, but I do not know what I have to share all edited text. Sharing a text editing field codes tell me.
Thanks
plz send m the code of:
how to share a transport app on the click of list view..
only transport application
How do you make that pop-up menu (The one in the image) come up?
Intent intent=new Intent();
Uri screenshotUri =Uri.parse(“android.resource://com.example.pddlaptophp.freindsquits/”+ back[inm[k]]);
//back[inm[k]] its array location store image
intent.setAction(Intent.ACTION_SEND);
ssintent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
ssintent.setType(“image/png”);
startActivity(Intent.createChooser(ssintent, “share image “));
share only massenger like whatsapp,linkdin.etc
not share gmail,Bluetooth,facebook
plz— help
Hi
I want to share a page from one user to another user of my app.Both users will get registered with my app and one of them should be able to share a page to another by using internet.I am a newbie..Please help
Thanks
Hi where can i find the complete code for this.
I want to share a contact through whatsapp, I used this code but nothing seems to work can you please help me?
Intent i = new Intent();
i.setType(“text/x-vcard”);
i.setAction(Intent.ACTION_SEND);
startActivity(Intent.createChooser(i,”Share via”));
break;
This way used to work for me, but not for all apps, whatsapp shows me messege “file format is not supported” is there another way?
Источник