给其他App发送简单的数据
在不痛的程序之间使用intent收发数据是社交分享内容时最常用的方法。Intent使用户能够通过最常用的程序进行快速简单的分享信息。
在构建一个intent时,必须指定这个intent需要触发的action。比如:ACTION_SEND,表明该intent用于从一个activity发送数据到另外一个activity,甚至可以是跨进程之间的数据发送。为了发送数据到另外一个activity,我们只需要指定数据与数据的类型,系统会自动识别出能够兼容接受的这些数据的activity。
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,"this is my text");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent,"Share to"));
在这里调用了Intent.createChooser(),创建了一个选择器,它会根据参数中的Intent的action来显示相应的选择界面。效果如下:
分享二进制内容
分享二进制的数据需要结合设置特定的MIME类型,需要在EXTRA_STREAM里面放置数据的URI。
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)));
发送多块内容
weile同时分享多种不同类型的内容,需要使用ACTION_SEND_MULTIPLE与指定到那些数据的URIs列表。MIME类型会根据分享的混合内容而不同。比如分享不同格式的图片,应该是用image/来匹配那些而已接收任何图片类型的activit。如果需要分享多种不同类型的数据,可以使用/*来表示MIME。(有些URI是需要访问权限的,记得添加权限)
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.."));
接收从其他App传送来的数据
Intent filters告诉android系统一个程序愿意接收的数据类型。
<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>
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
}
...
}