在 Android 中同时分享文字和图片

Share text and image at the same time in Android

几个小时以来,我一直在尝试与 Intent.ACTION_SEND 共享文本和图像(同时)。尽管我尽了一切努力让它发挥作用,但我仍然做不到。

我找遍了Google,这可能很奇怪,但我只找到了 2 个讨论如何同时分享文本和图像的帖子,我尝试了它们,但其中 none 有效。我尝试使用一种方法,结果如下:

Uri imageToShare = Uri.parse("android.resource://com.example.application/drawable/invite"); //Image to be shared
String textToShare = "Text to be shared"; //Text to be shared

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, textToShare);
shareIntent.setType("*/*");
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.putExtra(Intent.EXTRA_TEXT, imageToShare);
startActivity(Intent.createChooser(shareIntent, "Share with"));

希望以上信息对您有用。我仍然是 Java 的初学者,非常感谢任何帮助!

这对我有用:

Intent iShare = new Intent(Intent.ACTION_SEND);
iShare.setType("image/*");
iShare.putExtra(Intent.EXTRA_TEXT, "Your text”);
iShare.putExtra(Intent.EXTRA_STREAM, Your image);
startActivity(Intent.createChooser(iShare, "Choose app to share photo with!"));

首先,没有要求任何应用程序都支持通过 ACTION_SEND 共享文本和图像。

其次,图像的 Uri 进入 EXTRA_STREAM

第三,很少有应用程序知道如何将 android.resource 作为 Uri 方案来处理。毕竟那不是the documented scheme for an EXTRA_STREAM Uri。它必须是 content,您通过 ContentProvider 提供您的内容,例如 FileProvider

第四,如果您指定实际的 MIME 类型,而不是使用通配符,您的运气可能会更好。

我终于用更简单的方法做到了!我从图像创建了一个 base64 并将其作为字符串添加到 strings.xml 文件 中(确保从字符串的开头删除 data:image/png;base64,)。

我使用的代码如下:

byte[] decodedString = Base64.decode(getString(R.string.share_image), Base64.DEFAULT); //The string is named share_image.
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Uri imageToShare = Uri.parse(MediaStore.Images.Media.insertImage(MainActivity.this.getContentResolver(), decodedByte, "Share image", null)); //MainActivity.this is the context in my app.
String textToShare = "Sample text"; //Text to be shared

Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_TEXT, textToShare);
share.putExtra(Intent.EXTRA_STREAM, imageToShare);
startActivity(Intent.createChooser(share, "Share with"));

希望这个回答能解决很多人的问题!

非常感谢@notyou 和@CommonsWare

此代码将允许您发送任何带文本的位图图像。

Bitmap decodedByte = BitmapFactory.decodeResource(getResources(), R.drawable.refer_app);
            Uri imageToShare = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), decodedByte, "Share app", null));   // in case of fragment use [context].getContentResolver()
            String shareMessage = "message to share";
            Intent share = new Intent(Intent.ACTION_SEND);
            share.setType("image/*");
            share.putExtra(Intent.EXTRA_TEXT, shareMessage);
            share.putExtra(Intent.EXTRA_STREAM, imageToShare);
            startActivity(Intent.createChooser(share, "Share via"));