Android: 使用意图分享纯文本(到所有消息应用程序)

188

我正在尝试使用意图(Intent)分享一些文本:

Intent i = new Intent(android.content.Intent.ACTION_SEND);
i.setType("text/plain");  
i.putExtra(android.content.Intent.EXTRA_TEXT, "TEXT");

使用选择器进行扭曲:

startActivity(Intent.createChooser(sms, getResources().getString(R.string.share_using)));

它有效!但仅适用于电子邮件应用程序。
我需要一个通用意图,适用于所有消息传递应用程序:电子邮件、短信、即时通讯(WhatsApp、Viber、Gmail、SMS...)。尝试使用 android.content.Intent.ACTION_VIEW 和尝试使用 i.setType("vnd.android-dir/mms-sms"); 都没有帮助...

("vnd.android-dir/mms-sms" 只能与短信共享!)

10个回答

381

使用以下代码:

    /*Create an ACTION_SEND Intent*/
    Intent intent = new Intent(android.content.Intent.ACTION_SEND);
    /*This will be the actual content you wish you share.*/
    String shareBody = "Here is the share content body";
    /*The type of the content is text, obviously.*/
    intent.setType("text/plain");
    /*Applying information Subject and Body.*/
    intent.putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.share_subject));
    intent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
    /*Fire!*/
    startActivity(Intent.createChooser(intent, getString(R.string.share_using)));

7
但我不明白是什么造成了差异?只是外部的字符串吗? - skgskg
1
在模拟器上,我成功打开了消息应用,但在我的手机和平板电脑上,系统要求我从应用列表中选择。可能是因为在模拟器上需要安装额外的应用程序。 - Piyush-Ask Any Difference
好的回答!有人能告诉我为什么如果省略 sharingIntent.setType("text/plain"); 部分,它就无法工作吗? - NecipAllef
如何为Whatsapp设置单独的文本 - salih kallai
1
将以下代码片段添加到意图 sharingIntent.setPackage("com.whatsapp"); - Arpit Garg
谢谢你,兄弟。 - Bipin Bharti

72

现在可以使用ShareCompat.IntentBuilder来完成这个操作,如下:

// Create and fire off our Intent in one fell swoop
ShareCompat.IntentBuilder
        // getActivity() or activity field if within Fragment
        .from(this) 
        // The text that will be shared
        .setText(textToShare)
        // most general text sharing MIME type
        .setType("text/plain") 
        .setStream(uriToContentThatMatchesTheArgumentOfSetType)
        /*
         * [OPTIONAL] Designate a URI to share. Your type that 
         * is set above will have to match the type of data
         * that your designating with this URI. Not sure
         * exactly what happens if you don't do that, but 
         * let's not find out.
         * 
         * For example, to share an image, you'd do the following:
         *     File imageFile = ...;
         *     Uri uriToImage = ...; // Convert the File to URI
         *     Intent shareImage = ShareCompat.IntentBuilder.from(activity)
         *       .setType("image/png")
         *       .setStream(uriToImage)
         *       .getIntent();
         */
        .setEmailTo(arrayOfStringEmailAddresses)
        .setEmailTo(singleStringEmailAddress)
        /*
         * [OPTIONAL] Designate the email recipients as an array
         * of Strings or a single String
         */ 
        .setEmailTo(arrayOfStringEmailAddresses)
        .setEmailTo(singleStringEmailAddress)
        /*
         * [OPTIONAL] Designate the email addresses that will be 
         * BCC'd on an email as an array of Strings or a single String
         */ 
        .addEmailBcc(arrayOfStringEmailAddresses)
        .addEmailBcc(singleStringEmailAddress)
        /* 
         * The title of the chooser that the system will show
         * to allow the user to select an app
         */
        .setChooserTitle(yourChooserTitle)
        .startChooser();

如果您对使用ShareCompat有任何疑问,我强烈推荐来自Google Android Developer Advocate Ian Lake的此篇优秀文章this great article from Ian Lake,以获得更全面的API解释。正如你所注意到的,我从那篇文章中借用了一些例子。
如果那篇文章没有回答你的所有问题,总是可以在Android开发者网站上找到ShareCompat.IntentBuilder的Javadoc本身。我根据clemantiano的评论增加了这个API使用示例的更多内容。

1
除了这个答案之外,还有一些设置电子邮件地址收件人的方法,例如 setEmailBcc()setEmailCc() 和 **setEmailTo()**。 - clementiano
谢谢分享,但对我来说并不完美,有时候我会遇到这个异常 java.lang.IllegalArgumentException: Service not registered: ActivityInfo{67f62c5 com.google.android.apps.hangouts.phone.ShareIntentActivity}。 - berrytchaks

38

这是一个非常优秀的关于在Android中使用Intents分享的示例:

* 在Android中使用Intents进行分享

//Share text:

Intent intent2 = new Intent(); intent2.setAction(Intent.ACTION_SEND);
intent2.setType("text/plain");
intent2.putExtra(Intent.EXTRA_TEXT, "Your text here" );  
startActivity(Intent.createChooser(intent2, "Share via"));

//via Email:

Intent intent2 = new Intent();
intent2.setAction(Intent.ACTION_SEND);
intent2.setType("message/rfc822");
intent2.putExtra(Intent.EXTRA_EMAIL, new String[]{EMAIL1, EMAIL2});
intent2.putExtra(Intent.EXTRA_SUBJECT, "Email Subject");
intent2.putExtra(Intent.EXTRA_TEXT, "Your text here" );  
startActivity(intent2);

//Share Files:

//Image:

boolean isPNG = (path.toLowerCase().endsWith(".png")) ? true : false;

Intent i = new Intent(Intent.ACTION_SEND);
//Set type of file
if(isPNG)
{
    i.setType("image/png");//With png image file or set "image/*" type
}
else
{
    i.setType("image/jpeg");
}

Uri imgUri = Uri.fromFile(new File(path));//Absolute Path of image
i.putExtra(Intent.EXTRA_STREAM, imgUri);//Uri of image
startActivity(Intent.createChooser(i, "Share via"));
break;

//APK:

File f = new File(path1);
if(f.exists())
{

   Intent intent2 = new Intent();
   intent2.setAction(Intent.ACTION_SEND);
   intent2.setType("application/vnd.android.package-archive");//APk file type  
   intent2.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f) );  
   startActivity(Intent.createChooser(intent2, "Share via"));
}
break;

14
使用以下方法,只需将主题和正文作为该方法的参数传递。
public static void shareText(String subject,String body) {
    Intent txtIntent = new Intent(android.content.Intent.ACTION_SEND);
    txtIntent .setType("text/plain");
    txtIntent .putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
    txtIntent .putExtra(android.content.Intent.EXTRA_TEXT, body);
    startActivity(Intent.createChooser(txtIntent ,"Share"));
}

4
以下是适用于电子邮件或消息应用程序的代码。 如果通过电子邮件分享,则主题和正文都会被添加。
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                sharingIntent.setType("text/plain");

                String shareString = Html.fromHtml("Medicine Name:" + medicine_name +
                        "<p>Store Name:" + “store_name “+ "</p>" +
                        "<p>Store Address:" + “store_address” + "</p>")  .toString();
                                      sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Medicine Enquiry");
                sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareString);

                if (sharingIntent.resolveActivity(context.getPackageManager()) != null)
                    context.startActivity(Intent.createChooser(sharingIntent, "Share using"));
                else {
                    Toast.makeText(context, "No app found on your phone which can perform this action", Toast.LENGTH_SHORT).show();
                }

3

通过创建一个使用 ACTION_SEND 意图,您将能够添加额外参数类型为 Intent.EXTRA_TEXT,第二个参数是您要分享的文本。 然后通过将共享类型设置为 text/plain,意图服务将为您带来所有支持共享文本的应用程序。

Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");

Intent shareIntent = Intent.createChooser(sendIntent, null);
startActivity(shareIntent);

这只是从文档中复制粘贴而来。请提供更多关于以那种方式实现的信息。 - apex39
@apex39 我已经这样做了,谢谢。 - Abanoub Hany

1

图片或二进制数据:

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("image/jpg");
Uri uri = Uri.fromFile(new File(getFilesDir(), "foo.jpg"));
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri.toString());
startActivity(Intent.createChooser(sharingIntent, "Share image using"));

或者HTML:
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/html");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml("<p>This is the text shared.</p>"));
startActivity(Intent.createChooser(sharingIntent,"Share using"));

1

Kotlin

在需要添加此模块以通过应用程序(如WhatsApp,Gmail,Slack等)共享文本的单击侦听器内。

shareOptionClicked.setOnClickListener{
     val shareText = Intent(Intent.ACTION_SEND)
     shareText.type = "text/plain"
     val dataToShare = "Message from my application"
     shareText.putExtra(Intent.EXTRA_SUBJECT, "Subject from my application")
     shareText.putExtra(Intent.EXTRA_TEXT, dataToShare)
     startActivity(Intent.createChooser(shareText, "Share Via"))
     }

0

这段代码是用于通过短信分享的

     String smsBody="Sms Body";
     Intent sendIntent = new Intent(Intent.ACTION_VIEW);
     sendIntent.putExtra("sms_body", smsBody);
     sendIntent.setType("vnd.android-dir/mms-sms");
     startActivity(sendIntent);

0

适用于Gmail分享的100%工作代码

    Intent intent = new Intent (Intent.ACTION_SEND);
    intent.setType("message/rfc822");
    intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"anyMail@gmail.com"});
    intent.putExtra(Intent.EXTRA_SUBJECT, "Any subject if you want");
    intent.setPackage("com.google.android.gm");
    if (intent.resolveActivity(getPackageManager())!=null)
        startActivity(intent);
    else
        Toast.makeText(this,"Gmail App is not installed",Toast.LENGTH_SHORT).show();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接