Android Share Via Dialog

时间:2010-08-24 01:49:53

标签: android

我已经看过TFLN等应用中的“分享通过”对话框(昨晚的文字)。 看起来像这样:share dialog http://garr.me/wp-content/uploads/2009/12/sharevia.jpg

我希望分享文字。有人能指出我正确的方向吗?这是用意图完成的吗?

4 个答案:

答案 0 :(得分:109)

这确实是通过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"));

答案 1 :(得分:6)

我对接受的答案有疑问。对我有用的是从路径创建文件,然后解析文件的URI,如:

Uri.fromFile(new File(filePath));

而不是

Uri.parse(filePath)

万一有人遇到同样的问题。

答案 2 :(得分:4)

是。您需要为Activity提供一个intent过滤器,该过滤器可以处理MIME Type image / jpeg的对象(例如,如果您想支持共享JPEG图像),以及大概ACTION_SEND的操作。

许多内置的Android应用都是开源的,您可以查看Messaging应用的清单文件,看看它使用的是什么意图过滤器。

答案 3 :(得分:0)

引用: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
        }
    }
}