Lessons
-
Sending Simple Data to Other Apps
- Learn how to set up your application to be able to send text and binary data to other applications with intents. Receiving Simple Data from Other Apps
- Learn how to set up your application to receive text and binary data from intents. Adding an Easy Share Action
- Learn how to add a "share" action item to your action bar.
Sending Simple Data to Other Apps
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.
Send Text Content
Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send."); sendIntent.setType("text/plain"); startActivity(sendIntent);
However, if you call Intent.createChooser()
, passing it your Intent
object, it returns a version of your intent that will always display the chooser. This has some advantages:
- Even if the user has previously selected a default action for this intent, the chooser will still be displayed.
- If no applications match, Android displays a system message.
- You can specify a title for the chooser dialog.
Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send."); sendIntent.setType("text/plain"); startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
Send Binary Content
Binary data is shared using the ACTION_SEND
action combined with setting the appropriate MIME type and placing the URI to the data in an extra named EXTRA_STREAM
. This is commonly used to share an image but can be used to share any type of binary content:
Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage); shareIntent.setType("image/jpeg"); startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)));
Note the following: //共享二进制数据的两种方式 确保接收请求的app有权限去access文件
- You can use a MIME type of
"*/*"
, but this will only match activities that are able to handle generic data streams. - The receiving application needs permission to access the data the
Uri
points to. The recommended ways to do this are:- Store the data in your own
ContentProvider
, making sure that other apps have the correct permission to access your provider.The preferred mechanism for providing access is to use per-URI permissions which are temporary and only grant access to the receiving application. An easy way to create aContentProvider
like this is to use theFileProvider
helper class. - Use the system
MediaStore
. TheMediaStore
is primarily aimed at video, audio and image MIME types, however beginning with Android 3.0 (API level 11) it can also store non-media types (seeMediaStore.Files
for more info). Files can be inserted into theMediaStore
usingscanFile()
after which acontent://
styleUri
suitable for sharing is passed to the providedonScanCompleted()
callback.Note that once added to the systemMediaStore
the content is accessible to any app on the device.
- Store the data in your own
Send Multiple Pieces of Content
To share multiple pieces of content, use the ACTION_SEND_MULTIPLE
action together with a list of URIs pointing to the content. The MIME type varies according to the mix of content you're sharing. For example, if you share 3 JPEG images, the type is still "image/jpeg"
. For a mixture of image types, it should be "image/*"
to match an activity that handles any type of image. You should only use "*/*"
if you're sharing out a wide variety of types. As previously stated, it's up to the receiving application to parse and process your data. Here's an example:
ArrayList<Uri> imageUris = new ArrayList<Uri>(); imageUris.add(imageUri1); // Add your image URIs here imageUris.add(imageUri2); Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE); shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris); shareIntent.setType("image/*"); startActivity(Intent.createChooser(shareIntent, "Share images to.."));
As before, make sure the provided URIs
point to data that a receiving application can access.
Receiving Simple Data from Other Apps
Update Your Manifest
Intent filters inform the system what intents an application component is willing to accept. Similar to how you constructed an intent with action ACTION_SEND
in theSending Simple Data to Other Apps lesson, you create intent filters in order to be able to receive intents with this action. You define an intent filter in your manifest, using the <intent-filter>
element. For example, if your application handles receiving text content, a single image of any type, or multiple images of any type, your manifest would look like:
<activity android:name=".ui.MyActivity" > <intent-filter> <action android:name="android.intent.action.SEND" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.SEND" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="text/plain" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.SEND_MULTIPLE" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> </intent-filter> </activity>
Handle the Incoming Content
To handle the content delivered by an Intent
, start by calling getIntent()
to get Intent
object. Once you have the object, you can examine its contents to determine what to do next. Keep in mind that if this activity can be started from other parts of the system, such as the launcher, then you will need to take this into consideration when examining the intent(1).
void onCreate (Bundle savedInstanceState) { ... // Get intent, action and MIME type Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType(); if (Intent.ACTION_SEND.equals(action) && type != null) { if ("text/plain".equals(type)) { handleSendText(intent); // Handle text being sent } else if (type.startsWith("image/")) { handleSendImage(intent); // Handle single image being sent } } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) { if (type.startsWith("image/")) { handleSendMultipleImages(intent); // Handle multiple images being sent } } else { // Handle other intents, such as being started from the home screen(2) } ... } void handleSendText(Intent intent) { String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT); if (sharedText != null) { // Update UI to reflect text being shared } } void handleSendImage(Intent intent) { Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); if (imageUri != null) { // Update UI to reflect image being shared } } void handleSendMultipleImages(Intent intent) { ArrayList<Uri> imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); if (imageUris != null) { // Update UI to reflect multiple images being shared } },the wrong MIME type might be set, or the image being sent might be extremely large. Also, remember to process binary data in a separate thread rather than the main ("UI") thread.
Adding an Easy Share Action
Implementing an effective and user friendly share action in yourActionBar
is made even easier with the introduction ofActionProvider
in Android 4.0 (API Level 14). AnActionProvider
, once attached to a menu item in the action bar, handles both the appearance and behavior of that item. In the case of ShareActionProvider
, you provide a share intent and it does the rest.
Note: ShareActionProvider
is available starting with API Level 14 and higher.
Update Menu Declarations
To get started with ShareActionProviders
, define the android:actionProviderClass
attribute for the corresponding <item>
in yourmenu resource file:
<menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/menu_item_share" android:showAsAction="ifRoom" android:title="Share" android:actionProviderClass="android.widget.ShareActionProvider" /> ... </menu>This delegates responsibility for the item's appearance and function to
ShareActionProvider
.
However, you will need to tell the provider what you would like to share.
Set the Share Intent
In order for ShareActionProvider
to function, you must provide it a share intent. This share intent should be the same as described in the Sending Simple Data to Other Apps lesson,with action ACTION_SEND
and additional data set via extras like EXTRA_TEXT
and EXTRA_STREAM
. To assign a share intent, first find the correspondingMenuItem
while inflating your menu resource in your Activity
or Fragment
. Next, callMenuItem.getActionProvider()
to retrieve an instance of ShareActionProvider
. Use setShareIntent()
to update the share intent associated with that action item. Here's an example:
private ShareActionProvider mShareActionProvider; ... @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate menu resource file. getMenuInflater().inflate(R.menu.share_menu, menu); // Locate MenuItem with ShareActionProvider MenuItem item = menu.findItem(R.id.menu_item_share); // Fetch and store ShareActionProvider mShareActionProvider = (ShareActionProvider) item.getActionProvider(); // Return true to display menu return true; } // Call to update the share intent private void setShareIntent(Intent shareIntent) { if (mShareActionProvider != null) { mShareActionProvider.setShareIntent(shareIntent); } }
You may only need to set the share intent once during the creation of your menus, or you may want to set it and then update it as the UI changes. For example, when you view photos full screen in the Gallery app, the sharing intent changes as you flip between photos.