2.1.1 给其他 App 发送简单地数据
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));
分享二进制内容
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)));
接收从其他 App 传送来的数据
更新我们的 manifest 文件
我们可以创建 intent filters 来表明程序能够接收的 action 类型。
处理接收到的数据
可以通过 getIntent() 方法来获取到 Intent 对象 。如果一个 activity 可以被其他的程序启动,我们需要在检查 intent 的时候考虑这种情况(是被其他程序而调用启动的)。
请注意,由于无法知道其他程序发送过来的数据内容是文本还是其他类型的数据,若数据量巨大,则需要大量处理时间,因此我们应该避免在 UI 线程里面去处理那些获取到的数据。通过
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
}
来做判断并对应操作。
本文介绍了如何在Android应用中实现与其他应用之间的数据交互,包括发送简单文本数据、分享二进制内容如图片,并展示了如何接收来自其他应用的数据,以及如何在代码中处理这些接收到的数据。
2956

被折叠的 条评论
为什么被折叠?



