【发布时间】:2010-08-24 01:49:53
【问题描述】:
我在 TFLN 等应用中看到了“分享方式”对话框(昨晚的文字)。 看起来像这样:share dialog http://garr.me/wp-content/uploads/2009/12/sharevia.jpg
我希望分享文字。有人可以指出我正确的方向吗?这是有意图的吗?
【问题讨论】:
-
你能更新你链接的图片吗?它坏了。
标签: android
我在 TFLN 等应用中看到了“分享方式”对话框(昨晚的文字)。 看起来像这样:share dialog http://garr.me/wp-content/uploads/2009/12/sharevia.jpg
我希望分享文字。有人可以指出我正确的方向吗?这是有意图的吗?
【问题讨论】:
标签: android
这确实是用 Intents 完成的。
对于共享图像,如示例图片中,它会是这样的:
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
share.putExtra(Intent.EXTRA_STREAM,
Uri.parse("file:///sdcard/DCIM/Camera/myPic.jpg"));
startActivity(Intent.createChooser(share, "Share Image"));
对于文本,您可以使用以下内容:
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, "I'm being sent!!");
startActivity(Intent.createChooser(share, "Share Text"));
【讨论】:
我对接受的答案有疑问。对我有用的是从路径创建一个文件,然后解析文件的 URI,例如:
Uri.fromFile(new File(filePath));
而不是
Uri.parse(filePath)
以防万一有人遇到同样的问题。
【讨论】:
Uri.parse(filePath) 在一些应用程序中工作过(例如 Whatsapp 共享和 Dropbox),但在 Instagram、Gmail 和 Facebook 等应用程序中却失败了。 Uri.fromFile(new File(filePath)) 就像一个魅力,除了在 Gmail 中,它仍然失败,但我开始撰写电子邮件,我可以看到文件已正确附加。
是的。您需要为 Activity 提供一个意图过滤器,该过滤器可以处理 MIME 类型图像/jpeg 的对象(例如,如果您想支持共享 JPEG 图像),以及可能是 ACTION_SEND 的操作。
许多内置的 Android 应用程序都是开源的,您可以查看消息应用程序的清单文件以了解它使用了哪些意图过滤器。
【讨论】:
参考:Receiving simple data from other apps
更新您的清单
<activity android:name=".ui.MyActivity" >
//To receive single image
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
//To receive multiple images
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
处理传入的内容
public class MyActivity extends AppCompactActivity {
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 (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
}
}
}
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
}
}
}
【讨论】: